我试图弄清楚如何在使用 JOIN 语法时返回具有关联值的行,首先它应该检查 links
表以查看该行是否为 NULL
,如果它不是 NULL
,则将其用于 JOIN
,例如ON links.role_id = roles.role_id
如果该行是 NULl
。如果它是 NULL
,则使用 people
表。
我的语法:
SELECT roles.role_name
FROM
(
people_links links
LEFT OUTER JOIN people people ON links.person_id = people.person_id
LEFT OUTER JOIN roles roles ON links.role_id = roles.role_id OR links.role_id = people.role_id
)
基本上,当将 ON
语法与 role_id
一起使用时,它将返回来自 roles
表的关联值role_id
所以它应该依赖于 links
表 首先,检查 links.role_id
是否为 NULL
然后为 JOIN
返回 people.role_id
else links.role_id
以获取 role_name
。
当我运行此查询时,它首先使用 people
表中的 role_id
,而它应该首先查看 links
表。
我尝试使用 COALESCE
但它只会在应该返回 role_name
时返回 role_id
,例如(伪代码):
SELECT IF(links.role_id IS NOT NULL) links.role_id ELSE people.role_id ENDIF as join_value
FROM
(
people_links links
LEFT OUTER JOIN people people ON links.person_id = people.person_id
LEFT OUTER JOIN roles roles ON roles.role_id = join_value
)
最佳答案
您可以编写IF(links.role_id IS NOT NULL, links.role_id, people.role_id)
— 这是最接近您的伪代码的东西 — 但它更惯用编写 COALESCE(links.role_id, people.role_id)
。
有关IF
的信息,请参阅§11.4 "Control Flow Functions" in the MySQL Reference Manual ;有关 COALESCE
的信息,请参阅 §11.3.2 "Comparison Functions and Operators" .
关于mysql - 如果不为 NULL,则选择列,然后选择其他,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9568222/