Concatenate several fields into one with SQL

后端 未结 6 1787
再見小時候
再見小時候 2021-02-10 09:54

I have three tables tag, page, pagetag

With the data below

page

ID      NAME
1           


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-02-10 10:40

    I think you may need to use multiple updates.

    Something like (not tested):

    select ID as 'PageId', Name as 'PageName', null as 'Tags'
    into #temp 
    from [PageTable]
    
    declare @lastOp int
    set @lastOp = 1
    
    while @lastOp > 0
    begin
        update p
        set p.tags = isnull(tags + ', ', '' ) + t.[Tagid]
        from #temp p
            inner join [TagTable] t
                on p.[PageId] = t.[PageId]
        where p.tags not like '%' + t.[Tagid] + '%'
    
        set  @lastOp == @@rowcount
    end
    
    select * from #temp
    

    Ugly though.

    That example's T-SQL, but I think MySql has equivalents to everything used.

提交回复
热议问题