gpt4 book ai didi

mysql - 在 MySQL 中选择每个结果中最新的一个

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:02 26 4
gpt4 key购买 nike

如果我有一个与此类似但包含更多列和更多行的表格(这些是唯一相关的表格):

+-------+----+
| name | id |
+-------+----+
| james | 1 |
| james | 2 |
| james | 3 |
| adam | 4 |
| max | 5 |
| adam | 6 |
| max | 7 |
| adam | 8 |
+-------+----+

我怎样才能让它只显示每个 namemax(id),例如:

+-------+----+
| name | id |
+-------+----+
| adam | 8 |
| max | 7 |
| james | 3 |
+-------+----+

我目前只有这个

"select * from table order by id desc"

但这只是显示最新的 ID。我只想看到每个名字之一。


所以基本上只显示每个 name 的最高 id

最佳答案

您将使用聚合和 max():

select name, max(id)
from table t
group by name
order by max(id) desc
limit 40;

编辑:

如果您需要select * 具有最高的id,那么使用不存在方法:

select *
from table t
where not exists (select 1 from table t2 where t2.name = t.name and t2.id > t.id)
order by id desc
limit 40;

“不存在”实质上是说:“获取表中没有其他行具有相同名称和更高 ID 的所有行”。这是获得最大行的一种迂回方式。

关于mysql - 在 MySQL 中选择每个结果中最新的一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22109747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com