简体   繁体   中英

LEFT JOIN 2 INNER JOIN Tables Without Subquery

I have 3 Tables: Jobs, Users, Applications.

I'd like a list of all jobs and optionally "any" applications submitted per each job but only if I have data for the user who submitted the application.

I vaguely remember seeing some obscure syntax in which 2 tables are joined to a query as if being a single table, something like:

select j.title, a.id, u.name from jobs j
left join applications a join users u on a.job_id=j.id and a.user_id = u.id

I know I could accomplish this with a subquery, but does a syntax of this nature exist?

Update

The answers I've received so far assume I want only a basic join. Though they break the intended logic posed in the question. Perhaps I've should've posted the subquery equivalent to illustrate the type of query I'd like to run.

select j.job_id, au.application_id, au.user_id from jobs j
left join (
select a.job_id, u.user_id from applications a
join users u on u.user_id = a.user_id
) au on j.job_id = au.job_id

You were almost there, your only mistake was to put the both join conditions after the second join.

select * 
from jobs j
left join application a on on.job_id = j.id
left join users u on u.user_id = u.id

Note that the maximum number of tables that can be referenced in a join is 61 (in MySQL and probably most of the popular DBMS).

See documentation .

You need both of these to be outer joins if you chain them the "simple" way:

select * 
from jobs j
left outer join application a on a.job_id = j.id
left outer join users u on u.user_id = a.id

Since I take it that an application requires a user you can force the inner join to happen first in this way. Maybe that's the syntax question you were asking about. The parens are generally optional in my experience but I don't know a lot of MySQL:

select * 
from jobs j
left outer join (application a
inner join users u on a.user_id = u.id) on a.job_id = j.id

This is where a right join comes up sometimes so the query can be written from top to bottom without any nesting:

select * 
from application a 
inner join users u on u.user_id = a.id on 
right outer join jobs j on a.job_id = j.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM