我一直在寻找答案,我发现了CASE,IFF和UNION,但我还没有弄清楚,下面是我一直在尝试的。 / p>
SELECT *
FROM car_label as a
INNER JOIN car as b
ON a.label_id = b.label_id
WHERE a.car_id = 619
UNION ALL
SELECT *
FROM car
WHERE car_id = 619
如果第一个选择返回空,我想改为运行第二个选择。第一部分完美地运作,SELECT * FROM car_label as a INNER JOIN car as b ON a.label_id = b.label_id WHERE a.car_id = :car_id
,我只是试图包含第二个选择,以防第一个选择为空。
更新
Message: 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (SELECT * FROM car_label as a INNER JOIN car as' at line 1'
答案 0 :(得分:3)
试试这个:
SELECT *
FROM car_label as a
INNER JOIN car as b ON a.label_id = b.label_id
WHERE a.car_id = 619
UNION ALL
SELECT *
FROM car
WHERE car_id = 619
AND NOT EXISTS (SELECT 1
FROM car_label as a
INNER JOIN car as b ON a.label_id = b.label_id
WHERE a.car_id = 619)
因此,如果第一个查询返回任何数据,则NOT EXISTS
将为真,因此第二个查询条件为真,反之亦然。
请注意,为了使此查询起作用,返回的列应具有相同的计数和相同的数据类型,因此您可能需要列出列而不是*
。
然而,我认为您可能需要尝试LEFT JOIN
所以如果car_label
中没有匹配的汽车,您仍会从car
表中获取数据:
SELECT b.*
FROM car as b
LEFT JOIN car_label as a ON a.label_id = b.label_id AND a.car_id = 619
答案 1 :(得分:3)
我不太确定你的查询。据我了解,你可以去IF EXISTS
尝试下面
MSSQL
IF EXISTS(SELECT * FROM car_label as a INNER JOIN car as b ON a.label_id = b.label_id WHERE a.car_id = 619)
BEGIN
SELECT *
FROM car_label as a INNER JOIN car as b ON a.label_id = b.label_id
WHERE a.car_id = 619
END
ELSE
BEGIN
SELECT *
FROM car
WHERE car_id = 619
END
<强>的MySQL 强>
IF (SELECT * FROM car_label as a INNER JOIN car as b ON a.label_id = b.label_id WHERE a.car_id = 619) THEN
BEGIN
SELECT *
FROM car_label as a INNER JOIN car as b ON a.label_id = b.label_id
WHERE a.car_id = 619
END;
ELSE
BEGIN
SELECT *
FROM car
WHERE car_id = 619
END;
END IF;