简体   繁体   English

MySQL-获取不同的记录

[英]Mysql - getting distinct records

I have the following MySql table (user_actions) with the following columns: id, user_id, created_at, action_type 我有以下带有以下列的MySql表(user_actions):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. 我想要一个SQL查询,该查询将获得用户执行的最新操作,且操作没有重复。

for example: user_id 1 has 3 records that has the action_type "follow" and 2 records that has the action_type "unfollow" 例如:user_id 1有3条记录的动作类型为“ follow”,2条记录的动作类型为“ unfollow”

in this case i want the query to return two records, one with action_type "follow" and one with "unfollow" 在这种情况下,我希望查询返回两条记录,一条记录的action_type为“ follow”,一条记录的为“ unfollow”

any thoughts? 有什么想法吗?

You can use SQL's group by clause for this: 您可以为此使用SQL的group by子句:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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