Question

This is my database.

Tables:

item: item_id, name
order: order_id
orderform: order_id, item_id, quantity

Data in tables

item_id  name
1        ball
2        cap
3        bat

order_id
1
2
3
4

order_id item_id quantity
1        1       2
1        3       4
2        1       1
3        2       3
3        1       2
3        3       1
4        1       2

At the moment I'm using following sql query:

SELECT order_id, group_concat(name)
FROM order
LEFT JOIN orderform
  ON order.order_id = orderform.order__id
LEFT JOIN item
  ON orderform.item_id = item.item_id
GROUP BY order.order_id

Which gives me this look

order_id         name    
1                ball,ball,bat,bat,bat,bat
2                ball
3                cap,cap,cap,ball,ball,bat
4                ball,ball

But I want it to look like this

order_id  name
1         2 x ball,4 x bat
2         ball
3         3 x cap,2 x ball,bat
4         2 x ball
Was it helpful?

Solution

You have to go 2 steps:

First: Resolve the items and create the text

SELECT 
  orderform.order_id AS order_id,
  CONCAT(orderform.quantity, ' x ',item.name) AS txt
FROM order orderform
LEFT JOIN item ON orderform.item_id = item.item_id

then group by order

SELECT
  order_id, 
  group_concat(txt) AS txt
FROM (
    SELECT 
      orderform.order_id AS order_id,
      CONCAT(orderform.quantity, ' x ',item.name) AS txt
    FROM order orderform
    LEFT JOIN item ON orderform.item_id = item.item_id
) AS baseview
GROUP BY order_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top