[英]SQL - How to do an IF/ELSE in JOIN conditions
I know how to perform an IF/ELSE in the join conditions, but is there a way I can use a different evaluation of the field altogether based on the ELSE? 我知道如何在联接条件下执行IF / ELSE,但是有没有一种方法可以基于ELSE一起对字段进行完全不同的评估?
SELECT o.id, s.id
FROM orders o
RIGHT JOIN subjects s ON s.name = 'Blah'
AND s.group_id = IF(o.service = 'Law Services', 2, ????)
In the above, I don't know what to put at ????
在上面,我不知道要放什么
????
What I want to say is (pseudo code): 我想说的是(伪代码):
IF o.service = 'Law Services'
JOIN subjects s ON s.name = 'Blah' AND s.group_id = 2
ELSE
JOIN subjects s ON s.name = 'Blah'
Basically I only want to add the JOIN condition if s.group_id = 2
. 基本上,我只想在
s.group_id = 2
添加JOIN条件。
You can write the condition without an if
: 您可以编写条件而不使用
if
:
SELECT o.id, s.id
FROM orders o RIGHT JOIN
subjects s
ON s.name = 'Blah' AND
(o.service <> 'Law Services' or s.group_id = 2);
This may be worth a try: 这可能值得一试:
SELECT o.id, s.id
FROM orders o
RIGHT JOIN subjects s
ON s.name = 'Blah'
AND s.group_id = (CASE WHEN o.service = 'Law Services' THEN 2 ELSE s.group_id END)
SELECT o.id, s.id
FROM orders o
RIGHT JOIN subjects s ON s.name = 'Blah'
AND s.group_id = IF(o.service = 'Law Services', 2, s.group_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.