0

In this join query, i am multiplying two columns from different tables, premium & points. What i want to happen is if there are no columns joined in the premium table then the multiplier will be 1.

here is the query

 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

So if nothing is joined on the premiumtable instead of premiumtable.bid * pointstable.points it would be 1 * pointstable.points. The premiumtable.bid acts as a multiplier, if it isn't present, i'd want total to equal 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 に答える