sql字段合并mysql,使用SQL将多个字段合并为一个

I have three tables tag, page, pagetag

With the data below

page

ID NAME

1 page 1

2 page 2

3 page 3

4 page 4

tag

ID NAME

1 tag 1

2 tag 2

3 tag 3

4 tag 4

pagetag

ID PAGEID TAGID

1 2 1

2 2 3

3 3 4

4 1 1

5 1 2

6 1 3

I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output.

ID NAME TAGS

1 page 1 tag 1, tag 2, tag 3

2 page 2 tag 1, tag 3

3 page 3 tag 4

4 page 4

Is this possible with SQL?

I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.

解决方案Sergio del Amo:

However, I am not getting the pages without tags. I guess i need to write my query with left outer joins.

SELECT pagetag.id, page.name, group_concat(tag.name)

FROM

(

page LEFT JOIN pagetag ON page.id = pagetag.pageid

)

LEFT JOIN tag ON pagetag.tagid = tag.id

GROUP BY page.id;

Not a very pretty query, but should give you what you want - pagetag.id and group_concat(tag.name) will be null for page 4 in the example you've posted above, but the page shall appear in the results.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值