如何从表中获取每个id的最新状态?

时间:2018-06-14 05:15:59

标签: mysql sql node.js sequelize.js

考虑下表:

mysql> desc foo;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | NO   |     | NULL    |                |
| created_at | datetime     | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> desc bar;
+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int(11)      | NO   | PRI | NULL    | auto_increment |
| foo_id          | int(11)      | NO   | MUL | NULL    |                |
| status          | varchar(255) | YES  |     | NULL    |                |
| created_at      | datetime     | NO   |     | NULL    |                |
| updated_at      | datetime     | NO   |     | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

我想从条形图表中获取最近更新的foo_id和状态,而foo_id也包含多个状态

我尝试了以下查询:

SELECT foo_id, status
FROM bar d1
WHERE d1.updated_at =
    (SELECT MAX(d2.updated_at)
     FROM bar d2
     WHERE d1.foo_id = d2.foo_id)
GROUP BY foo_id
ORDER BY updated_at DESC;

在不同的计算机上出现以下错误:

  

未处理的拒绝SequelizeDatabaseError:SELECT的表达式#2   list不在GROUP BY子句中,并包含非聚合列   'dev.d1.status',它在功能上不依赖于列   GROUP BY子句;这与sql_mode = only_full_group_by

不兼容

如何从条形图表中获取每个foo_id的最新状态?

1 个答案:

答案 0 :(得分:3)

如果您只想要max updated_at的id,可以使用

select foo_id, status 
from bar 
where updated_at = (
select MAX(updated_at) 
from bar 
)

或使用联接

select foo_id, status 
from bar 
INNER JOIN (
select MAX(updated_at)  max_date
from bar 
) t on t.max_date  = bar.updated_at