SQL Join SELECT MAX,但也不存在值

时间:2017-04-12 09:33:02

标签: sql greatest-n-per-group

我有以下可用的SQL - 它显示所有项目以及MAX启动时间。

但是,我还想展示在播放列表中没有记录的项目 - 如何一个

SELECT items.idx, items.title, items.artist, playlistlog.starttime
FROM items
LEFT JOIN playlistlog ON playlistlog.item = items.idx
WHERE playlistlog.starttime = (
    SELECT MAX(starttime)
    FROM playlistlog AS pl2
    WHERE pl2.item = items.idx
)

2 个答案:

答案 0 :(得分:1)

where子句将左连接转换为内连接。

使用AND代替WHERE

SELECT items.idx, items.title, items.artist, playlistlog.starttime
FROM items
LEFT JOIN playlistlog ON playlistlog.item = items.idx
and playlistlog.starttime = (
    SELECT MAX(starttime)
    FROM playlistlog AS pl2
    WHERE pl2.item = items.idx
)

答案 1 :(得分:0)

使用标准SQL的窗口函数可以缩短这一点:

SELECT items.idx, items.title, items.artist, pl.starttime
FROM items
  LEFT JOIN (
    select item, 
           starttime, 
           row_number() over (partition by item order by starttime desc) as rn
    from playlistlog
  ) pl ON pl.item = items.idx AND pl.rn = 1