表1结构及数据
ID   NAME
1    zhangsan
2    lisi
3    wangwu
4    zhaoliu表2结构及数据
ID   Table_ID
1    1,2
2    2
3    3,4-------------------------------
如此,目前已得到表1的ID,如何寻找表2 Table_ID包含 表1ID的记录。求SQL 语句

解决方案 »

  1.   


    select * from 表2 where Table_ID in (select ID from 表1)
      

  2.   


    select * from table1 where exists(select 1 from table2 where ',' + cast(table1.id as nvarchar(10)) + ',' like ',' + cast(table2.table_id as nvarchar(10)) + ',')
    没测试,不好意思,参考参考。
      

  3.   

    我目前是已经得到表1的ID,要通过  Function code(ByVal str As String)这种方式去找表2的ID
    2楼兄弟的方法只能找到表2中 第二条记录,如果表2中的数据为“1,2,3,4”这样就找不到了。
      

  4.   

    select * from 表2 t where exists(select 'a' from 表1 y where instr(t.Table_ID||',',y.id||',')>0)
    在后面加“,”是防止取到二异数据,如Table_ID为12,1
      

  5.   

    另外我两个表是在两个不同的数据库中,所以只能先得到表1的数据,再去找表2的数据,不能将SQL语句写在一起
      

  6.   

    select * from 表2 where Table_ID in (select ID from 表1)
    引用一楼的SQL,此语句正确.
      

  7.   

    或者这问题问得不对,已知道一组数据
    1
    2
    3
    4
    5
    6
    如何通过得到的数据去找对应的表2的ID
    ID   ID2
    1    2
    2    1,3
    3    4,6,5
      

  8.   


    select * from table1 where 
    exists(
    select 1 from table2 
    where ',' + table2.T1_Id + ',' like
    ',%' + cast(table1.id as nvarchar(10)) + '%,' 

    )
    这个呢,是否满足?抱歉,上面弄反了
      

  9.   

    select * from 表2 where Table_ID in (select ID from 表1)
      

  10.   

       SQL = "select * from 表2 where ',' + Table_ID  + ',' like ',%" + str + "%,'"搞定,str=得到的ID