复杂的SQL查询

时间:2011-03-29 11:12:54

标签: sql sql-server oracle tsql

我正在尝试按照这些规则进行SQL查询:

基本上我有2个父表,A和B. B有一个名为C的子表,A有一个名为D的子表。 当我从B中选择一个值时,我从C获得一系列记录。 这个记录列表决定了我从A中提取的内容,然后我需要D中与A中提取的每条记录相关的所有信息。

我已经构建了一个查询来获取A中的记录,但是当你进入另一个级别时我会丢失。

SELECT A.ID
FROM (A
INNER JOIN A2
      ON A.IDV = A2.IDV
      AND A.Version = A2.CurrentVersion)
      LEFT JOIN C ON C.LANGUAGE = A.LANGUAGE
      INNER JOIN B ON C.PARENTID = B.ID
      WHERE (A2.Enabled = 1)
      AND (A.NUMBER = 00596205017)
      AND (B.NAME = 'BLAH');

提前致谢

[R

1 个答案:

答案 0 :(得分:4)

create table A (AID int)
create table B (BID int, AID int)
create table C (CID int, BID int)
create table D (DID int, AID int)

数据

insert into A values (1),(2),(3)
insert into B values (1, 1),(2, 1),(3, 2),(4, 3)
insert into C values (1, 1),(2, 1),(3, 2),(4, 3)
insert into D values (1, 1),(2, 1),(3, 2),(4, 3)

查询

select D.*
from A as A
  inner join D as D
    on A.AID = D.AID
where A.AID in (select B.AID
                from B as B
                  inner join C as C
                    on B.BID = C.BID)

结果

DID         AID
----------- -----------
1           1
2           1
3           2