table1:
ID RecordIndex FK1 FK2 FK3
1 1 73 131 1
2 1 74 163 1
3 1 75 169 1
4 1 76 NULL 1
5 2 73 132 1
6 2 74 167 1
7 2 75 171 1
8 2 76 NULL 1
9 3 73 131 1
10 3 74 163 1
11 3 75 171 1
12 3 76 NULL 1
----------------------------------------------
表内容如上。table1有三个外键FK1,FK2,FK3。
目的:找到符合条件的FK3
条件:
 RecordIndex相同的(condition1):FK1=73 and FK2=131 和 (condition2):FK1=74 and FK2=163。
期待结果:第1,2条记录匹配,而第1,10条则不匹配
不知道我说明白没有。condition 可能有很多:condition3,condition4....关键是在满足这些条件下,RecordIndex相同,这样的FK3该如何选择出来呢?

解决方案 »

  1.   


    declare @table1 table (ID int,RecordIndex int,FK1 int,FK2 int,FK3 int)
    insert into @table1
    select 1,1,73,131,1 union all
    select 2,1,74,163,1 union all
    select 3,1,75,169,1 union all
    select 4,1,76,null,1 union all
    select 5,2,73,132,1 union all
    select 6,2,74,167,1 union all
    select 7,2,75,171,1 union all
    select 8,2,76,null,1 union all
    select 9,3,73,131,1 union all
    select 10,3,74,163,1 union all
    select 11,3,75,171,1 union all
    select 12,3,76,null,1;with maco as(
    select * from @table1 where FK1=73 and FK2=131 
    union all
    select * from @table1 where FK1=74 and FK2=163) select distinct FK3 from maco where RecordIndex in (
    select RecordIndex from maco group by RecordIndex having(count(1)=2))
    /*
    FK3
    -----------
    1
    */
      

  2.   

    不就一个JOIN问题嘛--> 测试数据:#
    if object_id('tempdb.dbo.#') is not null drop table #
    create table #(ID int, RecordIndex int, FK1 int, FK2 int, FK3 int) insert into #
    select 1, 1, 73, 131, 1 union all
    select 2, 1, 74, 163, 1 union all
    select 3, 1, 75, 169, 1 union all
    select 4, 1, 76, null, 1 union all
    select 5, 2, 73, 132, 1 union all
    select 6, 2, 74, 167, 1 union all
    select 7, 2, 75, 171, 1 union all
    select 8, 2, 76, null, 1 union all
    select 9, 3, 73, 131, 1 union all
    select 10, 3, 74, 163, 1 union all
    select 11, 3, 75, 171, 1 union all
    select 12, 3, 76, null, 1-- 全部数据列出,a.FK3|b.FK3 随你取舍:
    select * from # a inner join # b on a.RecordIndex=b.RecordIndex
    where a.FK1=73 and a.FK2=131 and b.FK1=74 and b.FK2=163
    /*
    ID          RecordIndex FK1         FK2         FK3         ID          RecordIndex FK1         FK2         FK3
    ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
    1           1           73          131         1           2           1           74          163         1
    9           3           73          131         1           10          3           74          163         1
    */
      

  3.   

    对啊,自己join自己就行了,我真二。一楼写的有些高深。二楼很明确,多谢了