在此联接查询中,我将来自不同表格的两列相乘premium
& points
。我想要发生的是,如果premium
表中没有列加入,则乘数将为1.
这是查询
SELECT parent.*,(premiumtable.bid * pointstable.points) as total FROM strings parent
LEFT JOIN premium premiumtable on parent.sid=premiumtable.sid AND premiumtable.paid='1'
LEFT JOIN points pointstable on parent.sid=pointstable.`string-id`
WHERE parent.category=:category AND (parent.submittype='0' OR parent.submittype='3') GROUP BY parent.id ORDER BY total LIMIT 5
因此,如果premiumtable
上没有任何内容加入premiumtable.bid * pointstable.points
而不是1 * pointstable.points
,那么它就会premiumtable.bid
。 total
充当乘数,如果不存在,我希望pointstable.points
等于{{1}}
答案 0 :(得分:2)
使用case
声明:
SELECT parent.*,
case when premiumtable.bid is null
then pointstable.points
else premiumtable.bid * pointstable.points
end as total
FROM strings parent
LEFT JOIN premium premiumtable on parent.sid=premiumtable.sid AND premiumtable.paid='1'
LEFT JOIN points pointstable on parent.sid=pointstable.`string-id`
WHERE parent.category=:category
AND (parent.submittype='0' OR parent.submittype='3')
GROUP BY parent.id
ORDER BY total
LIMIT 5
答案 1 :(得分:1)
尝试使用COALESCE
:
SELECT parent.*,
(COALESCE(premiumtable.bid,1) * pointstable.points) as total
FROM strings parent
LEFT JOIN premium premiumtable
on parent.sid=premiumtable.sid AND premiumtable.paid='1'
LEFT JOIN points pointstable
on parent.sid=pointstable.`string-id`
WHERE parent.category=:category
AND (parent.submittype='0' OR parent.submittype='3')
GROUP BY parent.id
ORDER BY total LIMIT 5