[英]Nested if/else in MySQL select query
I am having a bit of trouble getting my syntax right for a nested mysql if statement. 我在为嵌套的mysql if语句获取语法时遇到了一些麻烦。 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) 基本上我需要将parentid位添加到我的查询中(用伪代码编写)
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: 您想使用
case
语句:
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. 这不仅可以做你想做的事情,而且它也是标准的SQL。 The
if
statement is specific to MySQL. if
语句特定于MySQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.