简体   繁体   中英

Aggregating strings across `group by` in SQL?

Consider the following schema:

create table A
(
    id int primary id
)

create table B
(
    a_id int,
    s varchar(255)
)

And then the following query:

select A.id, sum(1), ??? concat_join(B.s) ???
from A left join B on A.id = B.a_id group by A.id

There is a 1-to-many relation between A and B, so multiple rows will be grouped into one. The desired behaviour of "concat_join" would be for each Bs in the group join them together into a single string by concatenating them (perhaps with a space seperator).

Is there someway to express this is MySQL 5.5?

use GROUP_CONCAT

select A.id, sum(1), GROUP_CONCAT(B.s)
from A left join B on A.id = B.a_id 
group by A.id

by default, the string is separated by a comma . if you want to change it, add SEPARATOR keyword,

select A.id, sum(1), GROUP_CONCAT(B.s SEPARATOR ';')
from A left join B on A.id = B.a_id 
group by A.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM