小弟遇到一个难题先说明如下:    表一   TypeID      ClassID       typeName
          38             11           a
          39             11           b
          28             12           c    表二   id          BlogTypeList
          1             ~38~39
          2             ~38~40~89~56
          3             ~40~89~56
          4             ~12~34~34如上的2张表  现在查找出ClassID=11的 TypeID   38,39然后查出BLoggTypeList 里面含有 38  39  的id 。  

解决方案 »

  1.   

    select b.id
    from 表二 b
    left join 表一 a
    on b.BlogTypeList like '%'+a.TypeID+'%'
    where a.ClassID = 11
      

  2.   

     这是指BlogTypeList 包含38 或者39  
    但楼主如果要的是BlogTypeList 同时包含38和39  就不好使
      

  3.   

    select distinct b.id
    from t2 b
    left join t1 a
    on b.BlogTypeList like '%'+cast(a.TypeID as varchar)+'%'
    where a.ClassID = 11
      

  4.   


    --> 测试数据: #T1
    if object_id('tempdb.dbo.#T1') is not null drop table #T1
    create table #T1 (TypeID int,ClassID int,typeName nvarchar(255))
    insert into #T1
    select 38,11,'a' union all
    select 39,11,'b' union all
    select 28,12,'c'
    --> 测试数据: #T2
    if object_id('tempdb.dbo.#T2') is not null drop table #T2
    create table #T2 (id int,BlogTypeList nvarchar(255))
    insert into #T2
    select 1,'~38~39' union all
    select 2,'~38e40~89e56' union all
    select 3,'~40e89~56' union all
    select 4,'~12e34~34'
    select b.id
    from #T2 b left join #T1 a on (b.BlogTypeList like '%'+cast(a.TypeID as varchar(10))+'%') where a.ClassID = 11 GROUP BY b.id--现在查找出ClassID=11的 TypeID  38,39然后查出BLoggTypeList 里面含有 38  39  的id 
    --id
    -------------
    --1
    --2
      

  5.   

    select b.id
    from 表二 b
    left join 表一 a
    on b.BlogTypeList like '%'+a.TypeID+'%'
    where a.ClassID = 11
      

  6.   

    认为楼主的数据本身设计就有问题,为什么表二中BlogTypeList:  ~38~40~89~56 这样的就不能分开插入多条记录呢?要是这个BlogTypeList多含100个数据字,即使sql语句你能写出来,但分开来查询速度必然很慢的可以如下来写(当然ID可以不作为主键,那么就可以重复了):
    id  BlogTypeList
    1   38
    2   40
    3   89
    4   56 
      

  7.   

    try->
    select id from T2 a where exists(select 1 from T1 b where ClassID = 11
    and charindex(a.BlogTypeList+'~','~'+ltrim(b.TypeID)+'~')>0)
      

  8.   

    没环境不能试- -
    select id from T2 a where exists(select 1 from T1 b where ClassID = 11
    and charindex('~'+ltrim(b.TypeID)+'~',a.BlogTypeList+'~')>0)
      

  9.   

    --Code
    select id from @T2 a where exists(select 1 from @T1 b where ClassID = 11
    and charindex('~'+ltrim(b.TypeID)+'~',a.BlogTypeList+'~')>0)
    --Result
    /*
    id
    -----------
    1
    2
    */