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

如何在Yii2中对同一个表进行子查询,yii,Yii,如何使用yii2中的模型创建此查询 select *,p1.plan_id from product p1 where id in (select max(p2.id) from product p2 where p2.plan_id = p1.plan_id) id product_name plan_id ------------------------------- 1 bottle 1 2 book 2 3 bo

如何使用yii2中的模型创建此查询

select *,p1.plan_id from product p1 
    where id in (select max(p2.id) from product p2 where p2.plan_id = p1.plan_id)
id   product_name  plan_id
-------------------------------
1    bottle          1
2    book            2
3    book            2
4    bottle          1
5    notbook         3
形成下表产品

select *,p1.plan_id from product p1 
    where id in (select max(p2.id) from product p2 where p2.plan_id = p1.plan_id)
id   product_name  plan_id
-------------------------------
1    bottle          1
2    book            2
3    book            2
4    bottle          1
5    notbook         3

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

 $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";
在某些情况下,假设您的模型是name Product,findBySql可能会很有用

$models = Product::findBySql($sql)->all();
这个应该是您要执行的确切查询,但是

使用
join
s 因此,您应该使用
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();

此链接子查询中的可能重复项没有where条件,因此没有
Yii2雄辩的
。您想使用
ActiveRecord
还是只使用查询生成器创建查询?@shringiradwangan将
中的第一个参数更改为