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:
I think you had better add
data_idcolumn 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: