Concatenate several fields into one with SQL

后端 未结 6 1775
再見小時候
再見小時候 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:20

    I got a solution playing with joins. The query is:

    SELECT
        page.id AS id,
        page.name AS name,
        tagstable.tags AS tags
    FROM page 
    LEFT OUTER JOIN 
    (
        SELECT pagetag.pageid, GROUP_CONCAT(distinct tag.name) AS tags
        FROM tag INNER JOIN pagetag ON tagid = tag.id
        GROUP BY pagetag.pageid
    )
    AS tagstable ON tagstable.pageid = page.id
    GROUP BY page.id
    

    And this will be the output:

    id   name    tags
    ---------------------------
    1    page 1  tag2,tag3,tag1
    2    page 2  tag1,tag3
    3    page 3  tag4
    4    page 4  NULL
    

    Is it possible to boost the query speed writing it another way?

提交回复
热议问题