简体   繁体   English

SQL查询选择一对多关系中最新的两个表

[英]Sql query to select the most recent in one to many relationship two tables

I have a one to many relationship table such as customer to activities table as shown below Customer table 我有一对多关系表,例如客户到活动表,如下所示客户表

   Id  Name
   1   Customer 1
   2   Customer 2

Customer activities 客户活动

Id  customer_id activity created

1      1       Login    2017-01-01 10:52:32
2      1       Logout   2017-01-01 11:75:32
3      2       Post     2017-01-02 10:11:10
4      2       LogOut   2017-01-02 09:11:10

Let assume I have this repeated to thousand both customer table and customer activities. 假设我已经重复了数千次客户表和客户活动。 How can I write a single sql (using Mysql) to show the most recent record per each of the customer using created date such as having the result of activities below 如何编写单个sql(使用Mysql)以使用创建日期(例如,活动结果如下)显示每位客户的最新记录

Id  customer_id activity created

2      1       Logout   2017-01-01 11:75:32
3      2       Post     2017-01-02 10:11:10

example should be something like: 示例应类似于:

SELECT * 
FROM customer_activities 
WHERE created IN 
(
    SELECT MAX(created)
    FROM customer_activities 
    GROUP BY customer_id
);

But the above did not return the required result. 但是以上没有返回所需的结果。

Thanks. 谢谢。

You may use the subquery with aggregate and join 您可以使用子查询与骨料和join

select * 
from customer_activities  c
join (
   select customer_id, max(created) max_created
   from customer_activities 
   group by customer_id
) t on c.customer_id = t.customer_id and
       c.created = t.max_created

or in construct in结构

select * 
from customer_activities  c
where (customer_id, created) in (
   select customer_id, max(created) max_created
   from customer_activities 
   group by customer_id
) 

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

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