tags:

views:

36

answers:

1

Hi,

I am trying to perform a SELECT query using a GROUP BY clause, however I also need to access data from multiple rows and somehow concatenate it into a single column.

Here's what I have so far:

SELECT
COUNT(v.id) AS quantity, 
vt.name AS name, 
vt.cost AS cost, 
vt.postage_cost AS postage_cost 
FROM vouchers v 
INNER JOIN voucher_types vt 
ON v.type_id = vt.id 
WHERE 
v.order_id = 1 AND 
v.sold = 1 
GROUP BY vt.id

Which gives me the first four columns I need in the following format.

quantity | name | cost | postage_cost
2           X      5         1
2           Y      6         1

However, I would also like a fifth column to be displayed, showing all of the codes associated with each line of the order like this:

code
ABCD, EFGH
IJKL, MNOP

Where the comma separated values are pulled from the voucher table.

Is this possible? Any advice would be appreciated.

Thanks

+2  A: 

This is what GROUP_CONCAT does.

Assuming the column is called code you would just add ,GROUP_CONCAT(v.code) As Codes to your select list.

Martin Smith
Thanks! I'd never heard of that before
Dan