1

我已经准备好 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;
4

3 回答 3

0

用于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();


于 2019-11-20T05:51:46.090 回答
0

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

$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);
于 2019-11-20T05:09:02.297 回答
0

您可以使用选择

DB::select("your query");

你可以像下面这样传递参数(示例)

SELECT *  FROM `table` WHERE `id` > '$your_param'  ASC LIMIT 1
于 2019-11-20T05:23:52.507 回答