[英]How do I fetch the latest status of each id from table?
Consider the following table: 请考虑下表:
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)
I want to fetch the recently updated foo_id and status from the bar table and the foo_id consist of multiple status as well 我想从条形表中获取最近更新的foo_id和状态,并且foo_id也包含多个状态
I tried following query: 我尝试了以下查询:
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;
Got the following error on different machine: 在其他计算机上收到以下错误:
Unhandled rejection SequelizeDatabaseError: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'dev.d1.status' which is not functionally dependent on columns in GROUP BY clause;
未处理的拒绝SequelizeDatabaseError:SELECT列表的表达式#2不在GROUP BY子句中,并且包含未聚合的列'dev.d1.status',该列在功能上不依赖于GROUP BY子句中的列; this is incompatible with sql_mode=only_full_group_by
这与sql_mode = only_full_group_by不兼容
How do I fetch the latest status of each foo_id from bar table? 如何从条形表中获取每个foo_id的最新状态?
If you just want the id of the max updated_at you could use 如果您只想要最大updated_at的ID,则可以使用
select foo_id, status
from bar
where updated_at = (
select MAX(updated_at)
from bar
)
or using a join 或使用联接
select foo_id, status
from bar
INNER JOIN (
select MAX(updated_at) max_date
from bar
) t on t.max_date = bar.updated_at
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.