php 如何在Laravel中执行预准备语句

42fyovps  于 2022-12-10  发布在  PHP
关注(0)|答案(3)|浏览(157)

我已经准备好了SQL Prepared语句,当我在Workbench中运行它时,它们会给出正确的结果。现在我想在laravel中执行它。
SQL是:

SET SESSION group_concat_max_len = 1000000;

SET @SQL = NULL;
SELECT
    GROUP_CONCAT( DISTINCT CONCAT( 'MAX(IF( sp.PartnerID= ''', cep.PartnerID, ''', "Yes", "No")) AS ', REPLACE ( PartnerName, ' ', '' ) ) ) INTO @SQL 
FROM
    stp_partner sp,
    customer_eligible_partner cep,
    personal_loans pl,
    stp_partner_sub_product_mapping spm 
WHERE
    sp.PartnerID = cep.PartnerID 
    AND pl.PLAppId = cep.AppId 
    AND spm.PartnerID = sp.PartnerID 
    AND spm.SubProdCode = 1001;

SET @SQL = CONCAT( 'SELECT cep.AppId
    , cep.ProdCode
    , cep.CreatedDate, ', @SQL, ' 
    FROM customer_eligible_partner cep, stp_partner AS sp WHERE cep.PartnerID = sp.PartnerID AND cep.ProdCode = "1001" 
GROUP BY cep.AppId' );
PREPARE stmt 
FROM
    @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
kgqe7b3p

kgqe7b3p1#

您可以按如下方式执行查询

$sql =
        <<<EOF
SET SESSION group_concat_max_len = 1000000;

SET @SQL = NULL;
SELECT
    GROUP_CONCAT( DISTINCT CONCAT( 'MAX(IF( sp.PartnerID= ''', cep.PartnerID, ''', "Yes", "No")) AS ', REPLACE ( PartnerName, ' ', '' ) ) ) INTO @SQL 
FROM
    stp_partner sp,
    customer_eligible_partner cep,
    personal_loans pl,
    stp_partner_sub_product_mapping spm 
WHERE
    sp.PartnerID = cep.PartnerID 
    AND pl.PLAppId = cep.AppId 
    AND spm.PartnerID = sp.PartnerID 
    AND spm.SubProdCode = 1001;

SET @SQL = CONCAT( 'SELECT cep.AppId
    , cep.ProdCode
    , cep.CreatedDate, ', @SQL, ' 
    FROM customer_eligible_partner cep, stp_partner AS sp WHERE cep.PartnerID = sp.PartnerID AND cep.ProdCode = "1001" 
GROUP BY cep.AppId' );
PREPARE stmt 
FROM
    @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
EOF;
\DB::select($sql);
kfgdxczn

kfgdxczn2#

您可以使用SELECT

DB::select("your query");

您可以像下面这样传递param(示例)

SELECT *  FROM `table` WHERE `id` > '$your_param'  ASC LIMIT 1
qoefvg9y

qoefvg9y3#

对多个表使用leftjoin
并对该子查询使用\DB::raw

$sp_sql = \DB::table('stp_partner AS sp')
  ->leftjoin('customer_eligible_partner AS cep', 'sp.PartnerID', '=', 'cep.PartnerID')
  ->leftjoin('personal_loans AS pl', 'pl.PLAppId', '=', 'cep.AppId')
  ->leftjoin('stp_partner_sub_product_mapping AS spm', 'stp_partner_sub_product_mapping', '=', 'spm')
  ->where('spm.SubProdCode', 1001)
  ->selectRaw("GROUP_CONCAT( 
                 DISTINCT CONCAT( 
                   'MAX(IF( sp.PartnerID= ''', cep.PartnerID, ''', \"Yes\", \"No\")) AS ', REPLACE ( PartnerName, ' ', '' ) 
               )");

\DB::table('customer_eligible_partner AS cep')
  ->leftjoin('stp_partner AS sp', 'cep.PartnerID', '=', 'sp.PartnerID')
  ->where('cep.ProdCode', 1001)
  ->groupBy('cep_AppId')
  ->select('cep.AppId', 'cep.ProdCode', 'cep.CreatedDate', \DB::raw($sp_sql))
  ->get();

相关问题