【问题标题】:Sum multiple ActiveQuery subquery in select在选择中对多个 ActiveQuery 子查询求和
【发布时间】:2018-07-11 01:31:55
【问题描述】:

我有以下表格

产品

id name 
1  Alcohol
2  Candy
3  Soda

产品输入

id item_no count date
1  1       10   2018/01/01
2  1       20   2018/01/07
3  2       10   2018/01/08
4  3       10   2018/01/08

产品输出

id item_no count date 
1  1       10   2018/01/02 
2  1       10   2018/01/09 
3  2       2    2018/01/09
4  3       3    2018/01/11

我想得到产品实际数量的总和 通过做

select *, 
  (sum(select sum(count) from ProductIn where ProductIn.item_no = product.itemno) -
   sum(select sum(count) from ProductOut where ProductOut.item_no = product.itemno)) as availableQty
from product

目前我正在这样做,就像使用 ActiveQuery 一样

$main_query = Product::find();

$data = [];
foreach ($main_query->all() as $model) {
    $query1 = ProductIn::find()
                ->filterWhere(['=', 'item_code', $model->item_no])
                ->asArray()->one();

    $query2 = ProductOut::find()
                ->filterWhere(['=', 'item_code', $model->item_no])
                ->asArray()->one();

    $allModels[$model->item_no] = ['item_no' => $model->item_no, 'name' => $model->name,  'availableQty' => ($query1 - $query2)];
}

但是在每条记录上循环很慢我想结合 3 个 ActiveQuery。

我能够通过使用将子查询包含到 main_query 中

 $main_query->addSelect($query1)

但我无法将两个子查询的区别作为一个字段。

有没有办法在 ActiveQuery 上做到这一点?

【问题讨论】:

  • 也添加预期的查询结果。

标签: php activerecord yii2


【解决方案1】:

这里有一些建议给你-

  1. 无需在 forloop 中循环重复查询(即 $query1 和 $query2)
  2. ArrayHelper::getColumn 的帮助下,从$main_query 中收集ProductInProductOut 模型所需的所有item_codes
  3. 创建 2 个自定义数组以在其中存储 item_code 以及您的查询结果(数量/数量),并在您的 foreach 循环中使用此数组。

你会发现执行的时间差很大。

【讨论】:

    【解决方案2】:

    你可以试试这个查询:

    $connection = \Yii::$app->db;
    $model = $connection->createCommand('select *, 
      (sum(select sum(count) from ProductIn where ProductIn.item_no = product.itemno) -
       sum(select sum(count) from ProductOut where ProductOut.item_no = product.itemno)) as availableQty
    from product');
    $products = $model->queryAll();
    

    您需要导入查询类:

    use yii\db\Query;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      相关资源
      最近更新 更多