mysql在yii2中选择子查询

时间:2016-07-13 10:30:13

标签: mysql yii2

嗨,我想让这个

ID | Forename | Surname | Created
---------------------------------
 1 | Tom      | Smith   | 2008-01-01
 1 | Tom      | Windsor | 2008-02-01
 2 | Anne     | Thorn   | 2008-01-05
 2 | Anne     | Baker   | 2008-03-01
 3 | Bill     | Sykes   | 2008-01-20

变得像这样

ID | Forename | Surname | Created
---------------------------------
 1 | Tom      | Windsor | 2008-02-01
 2 | Anne     | Baker   | 2008-03-01
 3 | Bill     | Sykes   | 2008-01-20

所以我做了一个mysql查询:

SELECT 
  * 
FROM tableA as A 
WHERE created = (
    SELECT 
        MAX(created) 
    FROM tableA GROUP BY id having id=A.id
);

它也适用于mysql,我可以得到我想要的东西。

但我不知道如何在yii2 active

中写这个

我试过了:

 $query = (new \yii\db\Query())
                        ->select(['A.*'])
                        ->from('tableA AS A')
                        ->where('created = (SELECT MAX(created) from tableA GROUP BY id having id=A.id');

$command = $query->createCommand();
$data = $command->queryAll();

但它不起作用。

感谢。

2 个答案:

答案 0 :(得分:0)

顺便说一句,假设PK on(id,created),编写该查询的更好(即更有效)的方式是:

SELECT x.* 
  FROM my_table x 
  JOIN 
     ( SELECT id,MAX(created) created FROM my_table GROUP BY id ) y 
    ON y.created = x.created 
   AND y.id = x.id;

答案 1 :(得分:0)

试试这个

$subQuery = (new \yii\db\Query())
  ->select(['id', 'max_created' => 'MAX(created)'])
  ->from('tableA')
  ->groupBy('id'); 

$query = (new \yii\db\Query())
  ->select(['A.*'])
  ->from('tableA AS A')
  ->leftJoin(['B' => $subQuery], 'B.id = A.id')
  ->where('A.created = B.max_created');

$command = $query->createCommand();
$data = $command->queryAll();

您可以在此处获取详细信息:Yii2 guide section for Query->leftJoin

我在这里找到了相关主题: SELECT sub-query with WHERE condition in Yii2 find() / QueryBuilder