Get data if foreign key is NULL or NOT NULL

Viewed 70

I have 2 tables client and jobs.

In client table i have a foreign key job_id who get title in jobs.

But my job_id can be NULL or NOT NULL.

I want to get title if job_id IS NOT NULL and get NULL if job_id is NULL.

I try this request with IF() but this doesn't works

SELECT c.*, j.titre_poste FROM client c JOIN jobs j ON IF(c.job_id IS NOT NULL, c.job_id, c.job_id=j.id) WHERE c.archive=0

How can i do this ?

1 Answers

I think you want all rows from client even if there is no match. in jobs That suggests a LEFT JOIN:

SELECT c.*, j.titre_poste
FROM client c LEFT JOIN
     jobs j
     ON c.job_id = j.id
WHERE c.archive = 0
Related