SQL Management Studio选择特定的子项

时间:2010-11-02 12:37:11

标签: sql tsql join

所以我有三个表,table1table2table3。它们分别具有ID字段table1IDtable2IDtable3ID。此外,table2的字段table1ID指向table1中的一行,而table3的字段table2ID指向{{1}中的一行}}

所以,我的问题是,如何执行一个select语句,该语句仅选择table2中引用table3中引用table2中一行的ID的行中的行table1

1 个答案:

答案 0 :(得分:1)

您正在查看类似于此

的联接链接
select * from table3
join table2 on table3.table2ID = table2.table2ID
join table1 on table2.table1ID = table1.table1ID
where table1.ID = 4

如果匹配table2和表1记录,则只返回table3记录。连接将过滤连接匹配的结果,WHERE过滤器将仅从table1 ID = 4的结果中进行选择。

我掀起的工作样本(嘿,我有时间杀人)

create table #table1 (table1ID int)
create table #table2 (table2ID int, table1ID int)
create table #table3 (table3ID int, table2ID int)

insert into #table1 values(1)
insert into #table1 values(2)
insert into #table1 values(3)
insert into #table1 values(4)

insert into #table2 values(10, 1)
insert into #table2 values(11, 2)
insert into #table2 values(12, 3)
insert into #table2 values(13, 4)

insert into #table3 values(20, 10)
insert into #table3 values(21, 11)
insert into #table3 values(22, 12)
insert into #table3 values(23, 13)

-- all joined records
select * from #table3
join #table2 on #table3.table2ID = #table2.table2ID
join #table1 on #table2.table1ID = #table1.table1ID

-- only where table1 ID = 4
select * from #table3
join #table2 on #table3.table2ID = #table2.table2ID
join #table1 on #table2.table1ID = #table1.table1ID
where #table1.table1ID = 4

drop table #table1
drop table #table2
drop table #table3

这会给你

table3ID    table2ID    table2ID    table1ID    table1ID
----------- ----------- ----------- ----------- -----------
20          10          10          1           1
21          11          11          2           2
22          12          12          3           3
23          13          13          4           4

table3ID    table2ID    table2ID    table1ID    table1ID
----------- ----------- ----------- ----------- -----------
23          13          13          4           4