Nested Inner join query

此生再无相见时 提交于 2019-12-25 02:16:58

问题


I have four tables called attr, data, extradata and syst. I have to do multiple/nested inner joins to get some attributes from all 4 tables, and running into issues because of that. For some background, there is a column called 'ID' in 'data' table that I am obtaining by an inner join between data and extradata as follows:

Select X.ID FROM data X 
INNER JOIN extradata XA 
ON X.dataID = XA.dataID 
WHERE X.data = 'condition1' and NOT XA.additionaldata = 'condition2'

This ID has to be matched with the ID in attr table, and one more INNER join with syst table. The following is a very abbreviated version of the query that's I'm currently trying out:

SELECT TOP(10) a.ID 
FROM attr AS a 
INNER JOIN data AS X ON a.ID = 
(
    Select X.ID FROM data X 
    INNER JOIN extradata XA 
    ON X.dataID = XA.dataID 
    WHERE X.data = 'condition1' and NOT XA.additionaldata = 'condition2'
)
INNER JOIN syst AS s ON a.sysID = s.sysID
WHERE s.desc = 'condition3'

There is something (obviously) wrong with my query, so I'd be grateful for any suggestions. Thanks in advance!


回答1:


Assuming attr.ID maps to data.ID, you can simply join all of the tables together and all of the conditions go in your WHERE clause:

SELECT TOP(10) a.ID 
FROM attr AS a 
    INNER JOIN data AS X ON a.ID = x.ID
    INNER JOIN extradata XA ON X.dataID = XA.dataID
    INNER JOIN syst AS s ON a.sysID = s.sysID
WHERE X.data = 'condition1' 
  and NOT XA.additionaldata = 'condition2'
  and s.desc = 'condition3'

Joining attr to data allows you to also join attr to extradata, because data becomes the link between all 3.



来源:https://stackoverflow.com/questions/23207094/nested-inner-join-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!