开发者

SQL Management Studio Selecting specific children

So I have three tables, table1, table2, and table3. They each have ID fields, table1ID, table2ID, and table3ID respectively. Additionally, table2 has a field table1ID开发者_如何学JAVA which points to a row in table1, and table3 has a field table2ID which points to a row in table2.

So, my question is, how do I do a select statement that selects only the rows in table3 that reference a row in table2 that reference a row in table1 with the ID 4?


You're looking at a link of joins similar to this

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

this will only return table3 records if there is a matching table2 AND table 1 record. The join will filter the results out where the joins match, and the WHERE filter will only select from the results where table1 ID = 4.

A working sample I whipped up (hey I have time to kill)

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

This gives you

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜