ID NAME SECTION
1 joe driver
2 george technic
ID PERSONAL_ID EVENT DATE
1 1 idle November, 26 2014 12:28:52+0000
2 1 drive November, 26 2014 12:28:52+0000
3 1 idle November, 26 2014 12:28:52+0000
4 2 idle November, 26 2014 12:28:52+0000
5 2 idle November, 26 2014 12:28:52+0000
所以我想列出这里的个人及其最新日志:
ID NAME SECTION EVENT DATE
1 joe driver idle November, 26 2014 12:28:52+0000
2 george technic idle November, 26 2014 12:28:52+0000
我使用此查询
SELECT p.*, pl.event, pl.date
FROM personal p
RIGHT JOIN persoLog pl
ON p.id = pl.personal_id
我希望用唯一匹配的日志返回所有个人,但我得到了这个:
ID NAME SECTION EVENT DATE
1 joe driver idle November, 26 2014 12:40:24+0000
1 joe driver drive November, 26 2014 12:40:24+0000
1 joe driver idle November, 26 2014 12:40:24+0000
2 george technic idle November, 26 2014 12:40:24+0000
2 george technic idle November, 26 2014 12:40:24+0000
我做错了什么?
这是我的问题的SQLfiddle链接: http://sqlfiddle.com/#!2/da315a/2
答案 0 :(得分:1)
试试这个:
SELECT p.*,
pl.event, pl.date
FROM personal p
JOIN (
SELECT personal_id,max(date) as LastDate from persoLog
GROUP BY personal_id) x on p.id=x.personal_id
JOIN persoLog pl ON p.id = pl.personal_id
AND pl.date=x.lastDate
但是,在示例数据中,日志表中的所有日期都相同。解决这个问题,上面应该有效
答案 1 :(得分:0)
我相信这应该有效:
SELECT p.*, pl.event, pl.date
FROM personal p
LEFT JOIN persoLog pl ON p.id = pl.personal_id
GROUP BY p.id
ORDER BY date DESC