我正在尝试使用主查询的结果执行两个不同的内部联接,但是我不知道是否可能,我一直在搜索并发现CASE语句可以工作。
我一直在尝试if,但是我开始阅读文档,但这不是海豚
这是我的查询,希望任何人都可以帮助我或向我展示正确的方式。
SELECT * from suggestions INNER JOIN staff on suggestions.id_staff = staff.id_staff
(CASE
WHEN suggestions(suggestions.for_their_area = '1')
THEN (
INNER JOIN areas on staff.id_area = areas.id_area
)
ELSE (
INNER JOIN areas on suggestions.for_their_area = areas.id_area
)
) WHERE suggestions.accepted = '1'
如果我在一个字段中等于1的值执行第一个,而在同一字段中等于0则执行第二个表,我希望执行3个表的内部联接
答案 0 :(得分:1)
最好的方法是始终连接两个表,然后使用Case来决定使用哪个表。
SELECT s.*,
CASE WHEN s.for_their_area='1' THEN a1.area_field ELSE a2.area_field END area_field
FROM suggestions s
INNER JOIN staff st ON s.id_staff=st.id_staff
LEFT JOIN areas a1 on st.id_area=a1.id_area
LEFT JOIN areas a2 on s.for_their_area=a2.id_area
WHERE s.accepted='1'
或者您可以执行条件连接:
SELECT s.*,
a.area_field
FROM suggestions s
INNER JOIN staff st ON s.id_staff=st.id_staff
INNER JOIN areas a ON ((s.for_their_area='1' and st.id_area=a.id_area)
OR (s.for_their_area != '1' and s.for_their_area=a.id_area))
WHERE s.accepted='1'
答案 1 :(得分:0)
将条件移至ON
子句并使用LEFT JOIN
:
SELECT s.*, st.*,
COALESCE(a1.?, a2.?)
FROM suggestions s INNER JOIN
staff st
ON s.id_staff = st.id_staff LEFT JOIN
areas a1
ON st.id_area = a1.id_area AND
s.for_their_area = '1' LEFT JOIN
areas a2
ON s.for_their_area = a2.id_area AND
s.for_their_area <> '1'
WHERE s.accepted = '1';
对于要从areas
中选择的列,请使用COALESCE()
。
您也可以使用OR
来表达这种逻辑,但这通常是性能杀手。