简体   繁体   中英

Mysql - getting distinct records

I have the following MySql table (user_actions) with the following columns: id, user_id, created_at, action_type

I want a sql query that will get the latest actions that the user performed with no duplication of the actions.

for example: user_id 1 has 3 records that has the action_type "follow" and 2 records that has the action_type "unfollow"

in this case i want the query to return two records, one with action_type "follow" and one with "unfollow"

any thoughts?

You can use SQL's group by clause for this:

select user_id, action_type, max(created_at)
  from user_actions
 group by user_id, action_type

try this:

select ua.* 
from user_actions ua
join (select max(id) as max_id,user_id,action_type from user_action group by user_id,user_action) ua_max
on ua.id=ua_max.max_id and ua.user_id=ua_max.user_id and ua.action_type=ua_max.action_type

Try this query:

select * from user_actions where action_type, created_at in 
   (select action_type, max(created_at) from user_actions group by action_type);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM