简体   繁体   English

如何在多重表上执行SQL条件连接?

[英]How to do a sql conditional joining on multiples tables?

I have an already existing SQL request that join 8 tables togethers, I need to add 3 mores tables to add a facultative information to my data. 我已经有一个将8个表连接在一起的SQL请求,我需要添加3个mores表以向我的数据添加一些有益的信息。

For this task, we can ignore 6 tables (bundled in other_tables ) : 对于此任务,我们可以忽略6个表(捆绑在other_tables ):

数据库模式

The part in the red box is the one I got to add. 红色框中的部分是我必须添加的部分。 I want to only add request that respect a few conditions. 我只想添加尊重一些条件的request If none are found, I still want my person, but with no data in the Request column. 如果未找到任何人,我仍然想要我的人,但“ Request列中没有数据。

So far I tried this, but the multiple left join seems ugly and too inclusive. 到目前为止,我已经尝试过了,但是多个left join看起来很丑陋并且太包容了。

Select [...], request.Id
From [Action] inner join [other tables on ...] inner join
    Person on Action.PersonId = Person.Id left JOIN 
request as r on r.PersonId = Person.Id left JOIN
Subject as s on s.SubjectId = r.SubjectId left JOIN
TypeRequest tr on tr.IDSujet = s.SubjectId
Where 
([already existing conditions]) and typeRequest = 'MOVE' (?)

And to rephrase once more what I want : Get me all actions according to some filter (on other tables ), also get the person they are linked to. 再次表述我想要的内容:根据某个过滤器(在其他表上 )让我执行所有actions ,还获得与他们链接的person If that person has a Request of a specific TypeRequest , add the Request id to the data row. 如果这个person有一个Request一个特定的TypeRequest中,添加Request id的数据行。

Does the query above work? 上面的查询有效吗? "seems ugly and too inclusive" is a bit vague. “似乎丑陋且太包容”有点含糊。 are you getting the results you want? 您得到想要的结果吗? you can also move part of the where clause to the join like this: 您还可以像下面这样将where子句的一部分移到联接中:

    Select [...], request.Id
From [Action] inner join [other tables on ...] inner join
    Person on Action.PersonId = Person.Id left JOIN 
request as r on r.PersonId = Person.Id left JOIN
Subject as s on s.SubjectId = r.SubjectId left JOIN
TypeRequest tr on tr.IDSujet = s.SubjectId **and typeRequest = 'MOVE'**
Where 
([already existing conditions])

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

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