farfar009
farfar009

Reputation: 13

Select last rows from same name

I want to list fruit names from my table but I don't want to list more than one fruit name from the same user

my table looks like this

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

output should be like this;

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

I tried this code but it list first fruits

"SELECT * FROM mytable GROUP BY username DESC"

Upvotes: 1

Views: 752

Answers (5)

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

You can use correlated subquery :

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

Upvotes: 0

Nikhil
Nikhil

Reputation: 3950

this will also work apart from other answers:

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;

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

Upvotes: 0

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 31993

you could use 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
) 

Upvotes: 1

Fahmi
Fahmi

Reputation: 37473

You can use correlated subquery

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

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

Here is the "nice" way to do this with ROW_NUMBER, assuming you are using MySQL 8+:

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

On earlier versions of MySQL, we can join to a subquery which finds the most recent record for each 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;

Upvotes: 2

Related Questions