我有以下结构:
Attended:
id
user
date
Meetings:
id
data
place
Places
id
name
users
id
name
我正在尝试获取用户参加会议的最长日期,我可以通过运行以下内容来完成此操作:
select (meetings.date), places.name, meetings.id, attend.user
from attend
inner join meetings on meetings.Id = attend.meeting
inner join places on meetings.place = places.id
WHERE meetings.date IN (select max(meetings.date) from meetings)
但是,只有日期才是正确的,如果我尝试打印出该地点的名称,它将不是与会议相关联的地方与最大日期,但它实际上打印的地方有第一行我从出席表中获取。
根据会议日期查找最长出席日期的最佳方法是什么?
答案 0 :(得分:1)
你在找这样的东西吗?
SELECT a.user_name, a.meeting, a.place_name, a.date
FROM
(
SELECT a.user, a.meeting, m.date, p.name place_name, u.name user_name
FROM attended a JOIN meetings m
ON a.meeting = m.id JOIN places p
ON m.place = p.id JOIN users u
ON a.user = u.id
) a JOIN
(
SELECT a.user, MAX(m.date) date
FROM attended a JOIN meetings m
ON a.meeting = m.id
GROUP BY user
) q
ON a.user = q.user
AND a.date = q.date
ORDER BY user_name
示例输出:
| USER_NAME | MEETING | PLACE_NAME | DATE | -------------------------------------------------------------------- | User 1 | 2 | Place 2 | August, 11 2013 00:00:00+0000 | | User 2 | 1 | Place 1 | July, 12 2013 00:00:00+0000 | | User 3 | 1 | Place 1 | July, 12 2013 00:00:00+0000 |
这是 SQLFiddle 演示