2

Have warm wishes.

I have a table with lots of data and I need all data but the data that only updated last for example

Table

id  -   name    -   user_id -   email
1   -   abc     -   1   -   abc@email.com
2   -   xyz     -   2   -   xyz@email.com
3   -   abc     -   1   -   abc@email.com
4   -   pqr     -   3   -   pqr@email.com
5   -   abc     -   1   -   abc@email.com
6   -   pqr     -   4   -   pqr@email.com

And now i queryu something like this

SELECT MAX(id),* 
FROM `table`
GROUP BY user_id 
ORDER BY id DESC

But it not returns expected output.my expected output is

id  -   name    -   user_id -   email
5   -   abc     -   1   -   abc@email.com
2   -   xyz     -   2   -   xyz@email.com
4   -   pqr     -   3   -   pqr@email.com
6   -   pqr     -   4   -   pqr@email.com

The data inserted last only that will be shown. I refer this answer but it does not for getting all data. So how can I get all data that is inserted last when grouping id?

Dharman
  • 30,962
  • 25
  • 85
  • 135
TarangP
  • 2,711
  • 5
  • 20
  • 41

2 Answers2

2

You can use self join on same table to pick latest row per user

SELECT a.* 
FROM `table` a
JOIN (
    SELECT user_id , MAX(id) id
    FROM table
    GROUP BY user_id 
) b ON(a.user_id = b.user_id AND a.id = b.id)
ORDER BY a.id DESC

Demo

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
1

Especially if you are ordering the final results, you should consider a correlated subquery instead:

select t.*
from t
where t.id = (select max(t2.id)
              from table t2
              where t2.user_id = t.user_id
             )
order by t.id desc;

For performance, you want indexes on (user_id, id) and (id).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786