所以我有这个查询
SELECT IF(c2.nid IS NULL, c.*, c2.*) FROM table1 c LEFT JOIN table1 c2 ON c.cid = c2.pid WHERE c.pid = 0 AND c.nid = 674662;
请注意,c和c2都指的是table1 ....基本上,我想要它,如果存在左连接条目,它将返回左连接c2中的行,而如果它不存在,则将返回c1中的条目......
然而,执行此查询将产生mysql语法错误。我将如何完成我想要完成的任务(最好是在单个IF语句中)?
答案 0 :(得分:2)
我担心你不能在IF
陈述中使用星形图案。所以你需要明确地输入它,如
SELECT IF(c2.nid IS NULL, c.cid, c2.cid),
IF(c2.nid IS NULL, c.pid, c2.pid), ...
FROM table1 c LEFT JOIN table1 c2 ON c.cid = c2.pid
WHERE c.pid = 0 AND c.nid = 674662;
答案 1 :(得分:0)
正如@luksch的回答,您可以在所需的每一列上使用IF()
或COALESCE()
功能来完成此操作。
我能想到的唯一方法是使用UNION
并将这两种情况分开:
SELECT c2.*
FROM table1 c
INNER JOIN table1 c2 ON c.cid = c2.pid
WHERE c.pid = 0 AND c.nid = 674662
UNION ALL
SELECT c.*
FROM table1 c
LEFT JOIN table1 c2 ON c.cid = c2.pid
WHERE c.pid = 0 AND c.nid = 674662
AND c2.pid IS NULL ;