我有以下可用的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
)
答案 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