sql = "SELECT DISTINCT(p.*), concat(u.first_name,' ',u.last_name) as fullname, concat('@',u.username) as username, cover.file_path, cover.file_type, avatar.avatar_path
FROM products p
JOIN stores s ON s.id = p.store_id
JOIN users u ON u.id = s.user_id
LEFT OUTER JOIN (SELECT fh.product_id AS cp_id,
coalesce(fh.file_path, 'default image path') AS file_path,
fh.file_type AS file_type FROM file_handlers fh WHERE is_cover = true) cover ON p.id = cover.cp_id
LEFT OUTER JOIN (SELECT fh.id AS av_id, fh.file_path AS avatar_path FROM file_handlers fh WHERE is_cover = false) avatar ON u.avatar_id = avatar.av_id"
以上是我的postgresql数据库的原始sql查询。我的问题是,如果数据库中为null,我想显示默认的file_path。我尝试了三种方法:
1. COALESCE(fh.file_path, 'default image') AS file_path,
2. COALESCE(NULLIF(fh.file_path, ''), 'default image') AS file_path,
3. CASE WHEN fh.file_path IS NULL THEN 'default image' ELSE fh.file_path END AS file_path,
没有运气!它们都不适合我,我不知道为什么。我在这里缺少什么?
[注意:请参阅this screenshot]
答案 0 :(得分:2)
我很确定你的问题是由于左连接而不是合并。如果左连接没有产生任何行,cover.file_path
无论是否合并都会结束为空。
尝试将coalesce语句移动到更合适的位置:
sql = "SELECT DISTINCT(p.*), concat(u.first_name,' ',u.last_name) as fullname, concat('@',u.username) as username, coalesce(cover.file_path, 'default image path'), cover.file_type, avatar.avatar_path
FROM products p
...
答案 1 :(得分:0)
SELECT DISTINCT(p.*), concat(u.first_name,' ',u.last_name) as fullname,
CASE
WHEN
cover.file_path IS NULL AND cover.file_type='image'
THEN
'DEFAULT IMAGE PATH'
WHEN
cover.file_path IS NULL AND cover.file_type='audio'
THEN
'DEFAULT AUDIO PATH'
WHEN
cover.file_path IS NULL AND cover.file_type='video'
THEN
'DEFAULT VIDEO PATH'
ELSE
cover.file_path
END,
CASE
WHEN avatar.avatar_path IS NULL
THEN 'avatar.png'
ELSE avatar.avatar_path
END
FROM products p
JOIN stores s ON s.id = p.store_id
JOIN users u ON u.id = s.user_id
LEFT OUTER JOIN (SELECT fh.product_id AS cp_id, fh.file_path AS file_path, fh.file_type AS file_type FROM file_handlers fh WHERE is_cover = true) cover ON p.id = cover.cp_id
LEFT OUTER JOIN (SELECT fh.id AS av_id, fh.file_path AS avatar_path FROM file_handlers fh WHERE is_cover = false) avatar ON u.avatar_id = avatar.av_id
对我有用......是啊!