0

在此连接查询中,我将来自不同表的两列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

因此,如果没有加入,premiumtablepremiumtable.bid * pointstable.points不是1 * pointstable.points. premiumtable.bid充当乘数,如果不存在,我想total等于pointstable.points

4

2 回答 2

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
于 2012-09-15T16:45:09.760 回答
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
于 2012-09-15T16:45:20.627 回答