I am having a bit of trouble getting my syntax right for a nested mysql if statement. This is my current query which is fine. But what I need is the parent category. Heres where it confuses me.
Basically I need to add the parentid bit to my query (written in pseudo-code)
SELECT p.*,i.`image`,
( IF(`limitc1`.`parentid` IN (135,136), `limitc1`.parentid)
ELSEIF(`limitc2`.`parentid` IN (135,136), `limitc2`.parentid)
ELSEIF(`limitc3`.`parentid` IN (135,136), `limitc3`.parentid)
ELSEIF(`limitc4`.`parentid` IN (135,136), `limitc4`.parentid)
) as `parentid`
FROM `product` p
JOIN `productcategory` limitpc USING(productid)
LEFT JOIN `category` limitc1 ON (limitpc.`categoryid` = limitc1.`categoryid`)
LEFT JOIN `category` limitc2 ON (limitc1.`parentid` = limitc2.`categoryid`)
LEFT JOIN `category` limitc3 ON (limitc2.`parentid` = limitc3.`categoryid`)
LEFT JOIN `category` limitc4 ON (limitc3.`parentid` = limitc4.`categoryid`)
LEFT JOIN `productlink` l ON (p.`productid` = l.`targetid` OR p.`productid` = l.`sourceid`)
JOIN `productimage` i ON p.`productid` = i.`productid` AND i.`primary` = 1
WHERE (l.`sourceid` = 5471 OR l.`targetid` = 5471)
AND p.`visible` = 1
AND p.`websitevisible` = 1
AND p.`productid` != 5471
GROUP BY p.`productid`
LIMIT 8
Any ideas would be greatly appreciated! :-)
You want to use the case statement:
SELECT p.*,i.`image`,
(case when `limitc1`.`parentid` IN (135,136) then `limitc1`.parentid
when `limitc2`.`parentid` IN (135,136) then `limitc2`.parentid
when `limitc3`.`parentid` IN (135,136) then `limitc3`.parentid
when `limitc4`.`parentid` IN (135,136) then `limitc4`.parentid
end) as `parentid`
. . .
Not only does this do what you want to do, but it is also standard SQL. The if statement is specific to MySQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With