0

这是我的数据库。

表:

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

表格中的数据

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

目前我正在使用以下 sql 查询:

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

这让我看起来

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

但我希望它看起来像这样

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

1 回答 1

2

你必须走2个步骤:

第一:解析项目并创建文本

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

然后按顺序分组

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
于 2013-03-16T22:45:08.500 回答