乘以两列,不同的表......一列为空

时间:2012-09-15 16:42:47

标签: mysql sql

在此联接查询中,我将来自不同表格的两列相乘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.bidtotal充当乘数,如果不存在,我希望pointstable.points等于{{1}}

2 个答案:

答案 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