一张part表 id  partname 
1   网卡 
2  电源 
3  CPU 
4  机箱 
5  主板 一张partinfo表 
id   partid     brandname   price  
1      5          技嘉         800.0
2      5          华硕         700
3      4          LG          120
4      4          爱国者        200
5      3           金士顿       143一张 product表
id      name     pattern    desciption  partids
1        联想      e280      联想电脑     1,2,3,4,5
求一个产品的名称,型号,对应的partids下所有的品牌名,和价格.

解决方案 »

  1.   

    建议在前台应用中解决。
    先将partinfo表读到内存数组,
    将product的partids按逗号拆分,然后从partinfo数组取数据加总。
      

  2.   

    --> 测试数据: #part
    if object_id('tempdb.dbo.#part') is not null drop table #part
    create table #part (id int,partname varchar(4))
    insert into #part
    select 1,'网卡' union all
    select 2,'电源' union all
    select 3,'CPU' union all
    select 4,'机箱' union all
    select 5,'主板'
    --> 测试数据: #partinfo
    if object_id('tempdb.dbo.#partinfo') is not null drop table #partinfo
    create table #partinfo (id int,partid int,brandname varchar(6),price money)
    insert into #partinfo
    select 1,5,'技嘉',800.0 union all
    select 2,5,'华硕',700 union all
    select 3,4,'LG',120 union all
    select 4,4,'爱国者',200 union all
    select 5,3,'金士顿',143
    --> 测试数据: #product
    if object_id('tempdb.dbo.#product') is not null drop table #product
    create table #product (id int,name varchar(4),pattern varchar(4),desciption varchar(8),partids varchar(10))
    insert into #product
    select 1,'联想','e280','联想电脑','1,2,3,4,5'select a.*, c.partname, b.brandname, b.price
    from #product a, #partinfo b, #part c
    where charindex(','+ltrim(b.id)+',',','+a.partids+',')>0 and b.partid=c.id
    /*
    id          name pattern desciption partids    partname brandname price
    ----------- ---- ------- ---------- ---------- -------- --------- ---------------------
    1           联想 e280    联想电脑   1,2,3,4,5  主板     技嘉      800.00
    1           联想 e280    联想电脑   1,2,3,4,5  主板     华硕      700.00
    1           联想 e280    联想电脑   1,2,3,4,5  机箱     LG        120.00
    1           联想 e280    联想电脑   1,2,3,4,5  机箱     爱国者    200.00
    1           联想 e280    联想电脑   1,2,3,4,5  CPU      金士顿    143.00
    */
      

  3.   

    drop function dbo.fn_splitids 
    go
    create function dbo.fn_splitids ( @ids varchar(1000) )
    returns @idtb table ( id int )
    as begin
        declare @id int
        set @ids = rtrim(ltrim(@ids))
        while charindex(',', @ids)>0 begin
            set @id = left(@ids,charindex(',',@ids)-1)
            set @ids = right(@ids, len(@ids)-charindex(',',@ids))
            insert into @idtb values (@id)
        end
        if @ids>''
            insert into @idtb values (@ids)
        return
    end
    go
      

  4.   

    declare @dd nchar(50) ,@ddd nchar(4000) 
    set @dd='1,2,3,4,5'
    set @dd=','+'1,2,3,4,5'
    set @ddd=replace(@dd,',',' union all select * from partinfo where id=')
    exec right(rtrim(@ddd),len(rtrim(@ddd))-len(' union all '))