0

I create this SQL query:

SELECT * FROM favorite_user_cellphone fc
WHERE user_id = 123 AND unfavorited_at is null
ORDER BY favorited_at DESC;

the result of this query is below:

favorite_id  | user_id |  cellphone_id |  favorited_at        |   unfavorited_at
     7           123         1225       2019-04-13 12:35:02     null
     5           123         1225       2019-04-11 12:35:02     null
     2           123         1275       2019-04-09 13:00:02     null
     1           123         1225       2019-04-09 12:35:02     null

But now I would like to remove the duplicate rows (column cellphone_id) and keep the row with the most current date for each cellphone_id

So, the final result should be like this:

favorite_id  | user_id |  cellphone_id |  favorited_at        |   unfavorited_at
     7           123         1225       2019-04-13 12:35:02     null
     2           123         1275       2019-04-09 13:00:02     null

I do it:

SELECT * FROM favorite_user_cellphone fc
WHERE user_id = 123 AND unfavorited_at is null
ORDER BY favorited_at DESC;
André Ribeiro
  • 59
  • 2
  • 11

2 Answers2

1

You could use aggreagtion function max() and group by

SELECT max(favorite_id), user_id cellphone_id, max(favorited_at)  
FROM favorite_user_cellphone fc
WHERE user_id = 123 AND unfavorited_at is null
GROUP BY cellphone_id, user_id 
ORDER BY favorited_at DESC;

if you use select * all the records are returned also for info that can produce undesidered result .. so you should select only the columns you need applying aggregation functio for reduce result

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

Another solution, that you can run on your existing result table, might be:

select fuc.*
from favorite_user_cellphone fuc
inner join
(
   select cellphone_id, 
          max(favorite_id) as favorite_id
   from favorite_user_cellphone
   where user_id = 123
   group by cellphone_id
) t on fuc.favorite_id = t.favorite_id
Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82