I have two tables: users( user_id , country) and message( time_date , currency, amount_sold, message_user_FK ). The tables are in a 1:Many relationship ie each user can have multiple messages. 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 );
If you want the country with the latest date time, use a simple query . . . join
and 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.
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.