[英]mysql select latest timestamp for two matching rows with leftjoin
I have two tables in MySQL. 我在MySQL中有两个表。
The logs table has columns: time, user_id, event_type 日志表包含列:time,user_id,event_type
The users table has columns: email, id users表包含列:email,id
Every time a user logs in to the system that generates the logs file, the event_type column value is logged with the value '/dashboard'. 每次用户登录到生成日志文件的系统时,都会使用值“/ dashboard”记录event_type列值。
The select statement here will show my every time they logged in... 这里的select语句将显示我每次登录时...
SELECT users.email, logs.time
FROM users
LEFT JOIN logs ON users.id=logs.user_id
WHERE logs.event_type LIKE '/dashboard'
GROUP BY email, time;
...but I want to return the result set that shows the email address and timestamp for only the first time each user logged in. ...但我想返回结果集,该结果集仅显示每个用户首次登录时的电子邮件地址和时间戳。
You can use min
for that: 您可以使用min
:
SELECT users.email, min(logs.time)
FROM users
INNER JOIN logs ON users.id=logs.user_id
WHERE logs.event_type LIKE '/dashboard'
GROUP BY email;
Also no need for an outer join
-- you are negating that in your where
criteria. 也没有必要的outer join
-你是否定在你的where
标准。 If you want to keep the outer join
and return users that might not have matching records in the logs
table, then move the criteria to the on
: 如果要保留outer join
并返回logs
表中可能没有匹配记录的用户,请将条件移至on
:
SELECT users.email, min(logs.time)
FROM users
LEFT JOIN logs ON users.id=logs.user_id
AND logs.event_type LIKE '/dashboard'
GROUP BY email;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.