I have this problem:
I have two tables: one with user data and one with postal codes assigned to user (one user can have multiple postal codes).
Table with postal codes has two columns – start and end. First I need to select START and END and separate them eg. with -. I know I can use CONCAT_WS to do this, but I also need to take this concatenated strings (there are multiple rows) and concatenate them into one row.
I already have this query:
SELECT pc.user_id, CONCAT_WS('-', pc.start, pc.end) FROM postal_codes pc, users u WHERE u.id=pc.user_id
But s you expect it gives me results like this: (sorry I don’t know how to insert tables here)
row | user_id | postal range
============================
1 | 1 | AAAA-BBBB
----------------------------
2 | 1 | CCCC-DDDD
----------------------------
3 | 1 | MMMM-NNNN
----------------------------
4 | 2 | CCCC-DDDD
----------------------------
5 | 2 | EEEE-FFFF
----------------------------
and I need it to be like this:
row | user_ID | postal_range
----------------------------
1 | 1 | AAAA-BBBB, CCCC-DDDD, MMMM-NNNN
----------------------------
2 | 2 | CCCC-DDDD, EEEE-FFFF
----------------------------
I know I can use GROUP_CONCAT if i want to concatenate multiple rows – but if I wrap result of previous query into GROUP_CONCAT like this:
SELECT pc.user_id, (GROUP_CONCAT((SELECT CONCAT_WS('-', pc.start, pc.end) FROM bs_postal_codes pc, bs_users u WHERE u.id=pc.user_id) SEPARATOR ', ')) FROM bs_postal_codes pc
It gives me error: Subquery returns more than 1 row
It would really help me if someone give me a hand with this, thanks.
GROUP_CONCAT, as all aggregate functions, work within the query they are part of (the outer query). You cannot add a SELECT statement as a parameter that returns more than one row.
try this:
Addition (see comments):
1.
2.