我有这张桌子
id|name|number|date
1|peter|2|2017-09-18
2|peter|1|2017-10-03
3|james|4|2017-09-05
4|james|1|2017-10-10
5|james|0|2017-10-15
6|kate|4|2017-09-16
7|kate|2|2017-10-17
我想为每个人选择最新的行(具有最新日期的行)。结果看起来像
2|peter|1|2017-10-03
5|james|0|2017-10-15
7|kate|2|2017-10-17
哪个MYSQL查询可以做到这一点?
类似的东西:
SELECT id, name, number, date
FROM table
GROUP BY id, name, number, date
HAVING date the latest
答案 0 :(得分:0)
select t1.* from table t1, (select t2.name name2, max(t2.date)
date2 from table t2 group by t2.name) t3 where t1.name = t3.name2 and t1.date = t3.date2
答案 1 :(得分:0)
SELECT * FROM persons WHERE name='someone' order by date desc limit 1
这适用于按指定名称选择最新实体。
SELECT * FROM persons GROUP BY name, date ORDER BY date DESC
我用手机写的这个,可能是错的,但它的概念是正确的。
答案 2 :(得分:0)
MariaDB [test]> select * from stack s1 where s1.d = (select max(s2.d)
from stack s2 where s2.name = s1.name);
+------+-------+------+------------+
| id | name | num | d |
+------+-------+------+------------+
| 2 | peter | 1 | 2017-10-03 |
| 5 | james | 0 | 2017-10-15 |
| 7 | kate | 2 | 2017-10-17 |
+------+-------+------+------------+
3 rows in set (0.00 sec)
对于大型数据集,请不要忘记将索引添加到' name'并且' d'列。