[英]How can I find latest row (date and time) in 1 to many relation using JOIN
I have two tables: users( user_id , country) and message( time_date , currency, amount_sold, message_user_FK ). 我有两个表:users( user_id ,国家/地区)和message( time_date ,货币,amount_sold, message_user_FK )。 The tables are in a 1:Many relationship ie each user can have multiple messages.
这些表的关系为1:1,即每个用户可以有多个消息。 I would like to find the latest message for every country.
我想找到每个国家的最新消息。 I have the following query but it doesn't work.
我有以下查询,但不起作用。 What am i doing wrong?
我究竟做错了什么?
SELECT u.country, s.date_time
FROM users u
JOIN message s ON u.user_id = s.message_user_FK
JOIN(
SELECT message_user_FK ,MAX(date_time) date_time
FROM message
GROUP BY message_user_FK
) s1
ON(s.message_user_FK = s1.message_user_FK AND s.date_time = s1.date_time );
http://sqlfiddle.com/#!9/03858/20 http://sqlfiddle.com/#!9/03858/20
If you want the country with the latest date time, use a simple query . 如果您希望国家/地区具有最新的日期时间,请使用简单的查询。 .
。 .
。
join
and group by
: join
并group by
:
SELECT u.country, MAX(s.date_time)
FROM users u JOIN
message m
ON u.user_id = m.message_user_FK
GROUP BY u.country;
What's wrong with this? 这怎么了
SELECT u.country ,MAX(m.date_time) date_time
FROM users u
JOIN message m on u.user_id = m.message_user_FK
GROUP BY u.country
You subquery was close -- you were just grouping by the incorrect field. 您的子查询已关闭-您只是按错误的字段进行分组。 This would do the same.
这样做也一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.