SQL - 如何在JOIN条件下执行IF / ELSE

时间:2014-10-28 15:19:36

标签: mysql sql join

我知道如何在连接条件下执行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, ????)

在上文中,我不知道在????

放什么

我想说的是(伪代码):

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'

基本上我只想在s.group_id = 2添加JOIN条件。

3 个答案:

答案 0 :(得分:1)

您可以在没有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);

答案 1 :(得分:1)

这可能值得一试:

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)

答案 2 :(得分:0)

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)