我使用的是Postgres 9.6。我的数据库包含属于用户的演示文稿。每个演示文稿都有很多幻灯片。每张幻灯片可以选择有背景图片。Postgres:加入匹配的第一个非空值?
Table "public.presentation"
id │ integer
user_id │ integer
Table "public.slide"
id | integer
presentation_id | integer (foreign key)
index | integer
Table "public.background"
slide_id . | integer (foreign key)
image_id │ integer
我想取回文稿的列表为特定的用户,并与名称和每个演示的ID一起,我想获得具有第一张幻灯片的背景图片的ID背景图像(如果没有任何幻灯片具有背景图像,则为null)。这样我可以在每个演示文稿旁边显示缩略图。
目前,我有一个查询来获取第一张幻灯片的背景图像ID仅在演示文稿:
SELECT presentation.*, background.image_id
FROM presentation
JOIN -- get the first slide in each presentation
(SELECT presentation_id FROM slide WHERE index=0)
ON slide.presentation_id=presentation.id
LEFT OUTER JOIN -- join this with background (even if null)
background ON background.slide_id=slide.id
WHERE presentation.user_id=100
ORDER BY presentation.id;
但我想改变这种获得的第一个非空的背景图片ID每次演示。不知道如何做到这一点!
我想知道Postgres的first_value
可以帮助我吗?