如何将这个MySQL查询转换为Yii2 ActiveQuery格式?

时间:2016-06-17 04:41:00

标签: php yii2

这是我的MySQL查询

SELECT dc.`dc_key`
,@delivered_qty := (SELECT IFNULL(SUM(dd.`qty`),0)
    FROM `delivery_detail` dd
    WHERE dd.`item_key` = 1
    AND dd.dc_key = dc.dc_key
) AS delivered_qty
,@borrowed_qty := (SELECT IFNULL(SUM(bd.`qty`),0)
    FROM `borrow_detail` bd
    WHERE bd.`item_key` = 1
    AND bd.`voided` = 0
    AND bd.`returned` = 0
    AND bd.`dc_key` = dc.`dc_key`
) AS borrowed_qty
, (@delivered_qty - @borrowed_qty) AS available_qty
FROM `delivery_catalog` dc
WHERE (@delivered_qty - @borrowed_qty) > 0
LIMIT 1

这是我没有限制的结果 query result

这是我到目前为止所尝试的但没有好处。

$SQL = ''
. 'SELECT dc.`dc_key` '
. ',@delivered_qty := (SELECT IFNULL(SUM(dd.`qty`),0) '
. '    FROM `delivery_detail` dd '
. '    WHERE dd.`item_key` = :item_key '
. '    AND dd.dc_key = dc.dc_key '
. ') AS delivered_qty '
. ',@borrowed_qty := (SELECT IFNULL(SUM(bd.`qty`),0) '
. '    FROM `borrow_detail` bd '
. '    WHERE bd.`item_key` = :item_key '
. '    AND bd.`voided` = 0 '
. '    AND bd.`returned` = 0 '
. '    AND bd.`dc_key` = dc.`dc_key` '
. ') AS borrowed_qty '
. ', (@delivered_qty - @borrowed_qty) AS available_qty '
. 'FROM `delivery_catalog` dc '
. 'WHERE (@delivered_qty - @borrowed_qty) > 0 '
//. 'LIMIT 1 '
. '';

$rawData = DeliveryDetail::findBySql($SQL, [':item_key' => $item_key])->ALL();

print_r($rawData);

return;

它返回一个空数组。

我想利用yii2的查询构建器来获得干净的代码。

1 个答案:

答案 0 :(得分:1)

$SQL = ''
. 'SELECT dc.`dc_key` '
. ',@delivered_qty := (SELECT IFNULL(SUM(dd.`qty`),0) '
. '    FROM `delivery_detail` dd '
. '    WHERE dd.`item_key` = :item_key '
. '    AND dd.dc_key = dc.dc_key '
. ') AS delivered_qty '
. ',@borrowed_qty := (SELECT IFNULL(SUM(bd.`qty`),0) '
. '    FROM `borrow_detail` bd '
. '    WHERE bd.`item_key` = :item_key '
. '    AND bd.`voided` = 0 '
. '    AND bd.`returned` = 0 '
. '    AND bd.`dc_key` = dc.`dc_key` '
. ') AS borrowed_qty '
. ', (@delivered_qty - @borrowed_qty) AS available_qty '
. 'FROM `delivery_catalog` dc '
. 'WHERE (@delivered_qty - @borrowed_qty) > 0 '
//. 'LIMIT 1 '
. '';

$rows = \Yii::$app->db->createCommand($SQL)
            ->bindParam(":item_key", $item_key)
            ->queryAll();

应该有效。如果结果集很大,您可以通过query()使用datareader。

要使用查询构建器,您需要重写此查询,实际上可以在列中没有变量的情况下完成。

我认为这可以改写为:

SELECT dc.`dc_key` ,
IFNULL(SUM(dd.`qty`),0) as delivered_qty,
IFNULL(SUM(bd.`qty`),0) as borrowed_qty
LEFT JOIN `delivery_detail` dd ON dd.`item_key` = :item_key AND dd.dc_key = dc.dc_key 
LEFT JOIN `borrow_detail` bd ON 
         bd.`item_key` = :item_key 
    AND bd.`voided` = 0 
    AND bd.`returned` = 0 
    AND bd.`dc_key` = dc.`dc_key` 
FROM `delivery_catalog` dc
GROUP BY dc.`dc_key`
HAVING delivered_qty - borrowed_qty > 0 

(@delivered_qty - @borrowed_qty) AS available_qty这可以在PHP中完成,这样的查询可以毫无问题地转换为查询构建器。