简体   繁体   中英

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

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

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

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

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