简体   繁体   English

没有子查询的LEFT JOIN 2 INNER JOIN表

[英]LEFT JOIN 2 INNER JOIN Tables Without Subquery

I have 3 Tables: Jobs, Users, Applications. 我有3个表:作业,用户,应用程序。

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: 我隐约记得曾经看到过一些晦涩的语法,其中2个表联接到查询中,就好像是一个表一样,类似于:

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). 请注意,一个联接中可以引用的表的最大数量为61(在MySQL中,并且可能是大多数流行的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: 在我的经验中,括号通常是可选的,但我对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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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