简体   繁体   English

如何使用JOIN在1对多关系中找到最新行(日期和时间)

[英]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 : joingroup 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.

相关问题 我如何使用 PHP 在解析中建立一对多的关系 - How can i make one to many relation in parse using PHP 原则,如何连接具有多对多关系的表 - Doctrine, how to join tables with many to many relation php代码使用INNER JOIN语句计算一个数字连续出现多少次 - php code to count how many time a number appear in a row using INNER JOIN statement 如何在 Doctrine 中的多对多关系上执行 findBy? - How can i execute findBy on many to many relation in Doctrine? 如何在Laravel中更新“一对多”关系? (在文档中找不到) - How to update a “one to many” relation in Laravel? (can't find it in the docs) 如何使用querybuilder排除不具有多对多关系的实体,以Symfony2形式创建字段? - How can I make a field in a Symfony2 form, using querybuilder, excluding entities without a many-to-many relation? 如何使用select语句在php和mysql中获取最新的日期和时间 - how to get latest date and time in php and mysql using a select statement 如何从一对多关系中选择一条记录? - How can I pick single record from one to many relation? 我如何将表与第二个表的最新记录连接 - How can i join table with second table latest record 使用JOIN在mysql上找到一对多关系的最后一条记录 - find last record of one to many relation on mysql with JOIN
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM