代码之家  ›  专栏  ›  技术社区  ›  Entity

选择特定子项的SQL管理工作室

  •  0
  • Entity  · 技术社区  · 14 年前

    table1 , table2 ,和 table3 . 它们都有ID字段, table1ID table2ID ,和 table3ID 分别是。另外, 表2 指向一行 ,和 表3 表2id 表2 .

    表3 引用一行 表2 引用一行 表1 4 ?

    1 回复  |  直到 14 年前
        1
  •  1
  •   invert    14 年前

    你看到的连接类似于

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

    如果有匹配的table2和table 1记录,则只返回table3记录。联接将过滤出联接匹配的结果,而where过滤器将只从表1 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