我有以下查询,如果故事表中的每个mainMenu
,subMenu
和subMenu2
列都有值,则会产生正确的结果。
如果其中任何一个为null,则不返回任何结果。我不想使用左连接,因为当连接菜单处于非活动状态时,它将返回结果。
SELECT *
FROM stories s
JOIN menu m
ON s.mainMenu = m.id
AND m.menu_active = 1
JOIN submenu m2
ON s.subMenu = m2.id
AND m2.submenu_active = 1
JOIN submenu_L2 m3
ON s.subMenu2 = m3.id
AND m3.submenu_L2_active = 1
WHERE s.story_id = 198
AND s.story_active = 1
如果故事表中的相关列不为空,是否有办法只加入表?
类似于:
SELECT *
FROM stories s
if s.mainMenu IS NOT NULL then
JOIN menu m
ON s.mainMenu = m.id
AND m.menu_active = 1
end if
JOIN sub me...
答案 0 :(得分:0)
我同意Mukus。 听起来你想要LEFT JOIN。
LEFT JOIN将从表格“故事”中返回所有内容,并从表格“菜单”中返回他们加入的数据。
SELECT *
FROM stories s
LEFT JOIN menu m
ON s.mainMenu = m.id
AND m.menu_active = 1
LEFT JOIN sub me...
答案 1 :(得分:0)
我认为left outer join
子句中需要where
更多逻辑:
SELECT *
FROM stories s LEFT JOIN
menu m
ON s.mainMenu = m.id AND m.menu_active = 1 JOIN
submenu m2
ON s.subMenu = m2.id AND m2.submenu_active = 1 LEFT JOIN
submenu_L2 m3
ON s.subMenu2 = m3.id AND m3.submenu_L2_active = 1
WHERE s.story_id = 198 AND s.story_active = 1 AND
(s.mainMenue is null or m.id is not null);