I’m trying to figure how to return a row with the associated value when using the JOIN syntax, firstly it should check the links table to see if the row is NULL, if it’s not NULL use that for the JOIN e.g. ON links.role_id = roles.role_id if the row is NULl. If it’s NULL then use the people table.
My syntax:
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
)
Basically when joining and using the ON syntax with the role_id, it will return the associated value from the roles table that is used from the role_id so it should rely on the links table first, check if links.role_id is NULL then return people.role_id else links.role_id for the JOIN to get the role_name.
When I run this query, it uses the role_id from the people table first, when it should look in the links table first.
I tried using COALESCE but that will only return the role_id when it should return role_name, so for example (pseudo code):
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
)
You could write
IF(links.role_id IS NOT NULL, links.role_id, people.role_id)— that’s the closest thing to your pseudocode — but it’s more idiomatic to writeCOALESCE(links.role_id, people.role_id).For information on
IF, see §11.4 “Control Flow Functions” in the MySQL Reference Manual; for information onCOALESCE, see §11.3.2 “Comparison Functions and Operators”.