group_concat和此记录中每个单词的频率

时间:2013-03-16 22:35:28

标签: mysql sql word-frequency

这是我的数据库。

表:

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

1 个答案:

答案 0 :(得分: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