如何在Yii2口才中对同一表进行子查询

时间:2018-07-14 11:45:02

标签: yii

如何使用 yii2

中的模型创建此查询
models.Task.create({...args}, { searchPath: 'clienta' })

形成下表产品

select *,p1.plan_id from product p1 
    where id in (select max(p2.id) from product p2 where p2.plan_id = p1.plan_id)

2 个答案:

答案 0 :(得分:0)

您可以使用内部联接重构查询,例如:

 $sql = "select *
    from product p1 
    inner join (
      select plan_id, max(id) max_id 
      from product 
      group by plain_id
    ) t on t.plan_id = p1.plan_id and p1.id = t.max_id";

,并且在某些情况下,如果您的模型名为Product,则findBySql可能会很有用

$models = Product::findBySql($sql)->all();

答案 1 :(得分:0)

是您将会执行的确切查询 it won't work for MySQL

// select *, p1.plan_id from product p1
//     where id in (select max(p2.id) from product p2 where p2.plan_id = p1.plan_id)

$subquery = (new \yii\db\Query)->select('[[p2]].[[id]]')
    ->from(['p2' => 'product'])
    ->where('[[p2]].[[plan_id]] = [[p1]].[[plan_id]]')
    ->orderBy('[[p2]].[[id]] DESC')->limit(1); // equiv to max(p2.id)

$query = (new \yii\db\Query)->from(['p1' => 'product'])
    ->where(['p1.id' => $subquery])
    ->one();

// PS: Yii will quote fields wrapped in `[[]]` double square-brackets.

使用join

因此,您应该使用innerJoin(或其他变体)来实现适用于任何数据库的相同结果:

$query = (new \yii\db\Query)->from(['p1' => 'product'])
    ->innerJoin(['product p2'], '[[p2]].[[plan_id]] = [[p1]].[[plan_id]]')
    ->orderBy('[[p2]].[[id]] DESC')->limit(1); // equiv to max(p2.id)
    ->one();