T1id   name
1     n1
2     n2
3     n3
4     n4
5     n5
T2tid  xid
1,3   2
2     2
2,4   2
4     3
1,5   5查询xid=2 所有t1的纪录
id   name
1     n1
2     n2
3     n3
4     n4
查询xid=3 所有t1的纪录
4     n4
查询xid=5 所有t1的纪录1     n1
5     n5用一条语句实现 如何实现?  

解决方案 »

  1.   


    select * from T1 
    where
    exists(select 1 from T where xid=2 and charindex(','+rtrim(t1.ID)+','),','+tid+',')>0)
    ---或
    select * from T1 
    where
    exists(select 1 from T where xid=2 and ','+tid+',' like '%,'+rtrim(t1.ID)+',%'>0)
      

  2.   


    select * from T1 
    where
    exists(select 1 from T where xid=2 and charindex(','+rtrim(t1.ID)+','),','+tid+',')>0)
    ---或
    select * from T1 
    where
    exists(select 1 from T where xid=2 and ','+tid+',' like '%,'+rtrim(t1.ID)+',%')
      

  3.   

    select distinct t1.*
    from t1 , t2
    where ','+t2.tid+',' like '%,'+t1.id+',%' 
          and t2.xid = 2
      

  4.   

    declare @T1 table(id int,  name nvarchar(5))
    insert @T1 select  1,    'n1' 
    insert @T1 select  2,           'n2' 
    insert @T1 select  3,           'n3' 
    insert @T1 select  4,           'n4' 
    insert @T1 select  5,           'n5' 
    declare @T2 table(tid nvarchar(5),     xid int)
    insert @T2 select '1,3',       2 
    insert @T2 select '2'  ,         2 
    insert @T2 select '2,4' ,      2 
    insert @T2 select '4'    ,       3 
    insert @T2 select '1,5'   ,    5 
    select   *   from   @T1  t1  
    where 
    exists(select   1   from   @T2 t2   where   xid=2   and   charindex(','+rtrim(t1.ID)+',',','+tid+',')> 0) select   *   from   @T1  t1  
    where 
    exists(select   1   from   @T2 t2   where   xid=3   and   charindex(','+rtrim(t1.ID)+',',','+tid+',')> 0) select   *   from   @T1  t1  
    where 
    exists(select   1   from   @T2 t2   where   xid=5   and   charindex(','+rtrim(t1.ID)+',',','+tid+',')> 0) (所影响的行数为 1 行)
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)id          name  
    ----------- ----- 
    1           n1
    2           n2
    3           n3
    4           n4(所影响的行数为 4 行)id          name  
    ----------- ----- 
    4           n4(所影响的行数为 1 行)id          name  
    ----------- ----- 
    1           n1
    5           n5(所影响的行数为 2 行)