选择相同名称的最后几行

时间:2019-04-17 09:41:19

标签: mysql sql

我想从表中列出水果名称,但是我不想列出来自同一用户的多个水果名称

我的桌子看起来像这样

id     |    username         |  fruits
------------------------------------------
1      |    John             |  strawberry
2      |    Nick             |  banana
3      |    Ben              |  apple
4      |    Nick             |  pear
5      |    John             |  cherry

输出应该是这样;

5  |  John     |    cherry
4  |  Nick     |    pear
3  |  Ben      |    apple

我尝试了这段代码,但是列出了第一个成果

"SELECT * FROM mytable GROUP BY username DESC"

5 个答案:

答案 0 :(得分:2)

假设您使用的是MySQL 8+,这是ROW_NUMBER做到这一点的“不错”方法:

SELECT username, fruits
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY username ORDER BY id DESC) rn
    FROM yourTable
) t
WHERE rn = 1;

在早期版本的MySQL上,我们可以加入一个子查询,该子查询查找每个username的最新记录:

SELECT t1.username, t1.fruits
FROM yourTable t1
INNER JOIN
(
    SELECT username, MAX(id) AS max_id
    FROM yourTable
    GROUP BY username
) t2
    ON t1.username = t2.username AND
       t1.id = t2.max_id;

答案 1 :(得分:1)

您可以使用in

SELECT a.username, a.fruits
FROM table_name a
where (a.username,a.id) in
(
    SELECT username, MAX(id) as mid 
    FROM table_name
    GROUP BY username
) 

答案 2 :(得分:0)

您可以使用相关子查询

select id,username, fruits
from tablename a
where id in (select max(id) from tablename b where a.username=b.username)

答案 3 :(得分:0)

这也可以与其他答案分开:

select `username`,`fruits` from (select `id12`,`username`,`fruits`,RANK() over 
(PARTITION  by `username`
order by `id12` desc )as rn   from Table1)m where rn=1;

检查:https://www.db-fiddle.com/f/vmWYczLQLanhvcqChuRL4b/0

答案 4 :(得分:0)

您可以使用相关子查询:

select t.*
from table t
where t.id = (select max(t1.id) from table t1 where t1.username = t.username);