简体   繁体   中英

mySql Select last entry for each user

I have two tables:

users:
user_id    user_name

data:
user_id    user_data    user_time

I wan to select the latest entry from the data table, but return the user_name, user_id, user_data and user_time .

I have tried the following query, but it returns the first entry, not the last for each user:

sql = "SELECT users.user_name, users.user_id, data.user_data, data.user_time
FROM users 
INNER JOIN data ON data.user_id = users.user_id
GROUP BY users.user_name
ORDER BY data.user_time DESC";

Use GROUP BY and MAX, WHERE...IN:

SELECT u.user_id, u.user_name, d.user_data, d.user_time
FROM users u
    INNER JOIN data d ON d.user_id = u.user_id
WHERE (d.user_id, d.user_time) = 
    (SELECT user_id, MAX(user_time) FROM data GROUP BY user_id)

I think you had better add data_id column to data table. Unless data_id, both user_id and user_time are necessary for PRIMARY KEY (and user_time is not always unique, not reliable)

If there is data_id, it can be bitly simple:

SELECT u.user_id, u.user_name, d.user_data, d.user_time
FROM users u
  INNER JOIN data d ON d.data_id =
    (SELECT data_id FROM data
       WHERE user_id = u.user_id ORDER BY data_time DESC LIMIT 1) 

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