连接多个列并在一行内排序

时间:2014-06-04 15:51:15

标签: mysql sorting group-by concatenation group-concat

我有一个包含以下字段的表:

+------------------------------+
|  id  | cart1 | cart2 | cart3 |
|------------------------------|
|  1   |  ball |  soap |  NULL |
|  2   | apple | towel | paper |
|  3   |  soap |  ball |  NULL |
| .... | ..... | ..... | ..... |
+------------------------------+

我想要以下输出:

+-----------------------------------------+
| item1 | item2 | item3 | num_appearances |
|-----------------------------------------|
| ball  | soap  |  NULL |        2        |
| apple | towel | paper |        1        |
| ..... | ..... | ..... | ............... |
+-----------------------------------------+

基本上,cart1cart2cart3定义了某个人的购物车,但订单并不重要,我想要计算这个数字有些项目是一起购买的,再次订购无关紧要。因此appletowelpaper在示例表中出现一次,ballsoap出现了两次。

我认为我需要做的是排序item1item2item3,将它们连接起来,然后按该连接值进行分组。所以group_concat听起来很棒,我可以按id分组,或者对每一行都有不同的其他列。但到目前为止,我有group_concat(item1, item2, item3 [ORDER BY WHAT])。但是,如何对列列表进行排序并返回该连续排序列表?

2 个答案:

答案 0 :(得分:1)

将@ Strawberry的建议与我的“崩溃”想法相结合。

SELECT  combo, COUNT(combo) total
FROM
(
    SELECT  id, GROUP_CONCAT(item ORDER BY item) combo
    FROM
    (
        SELECT  id, item1 item
        FROM    cart_table
        UNION ALL
        SELECT  id, item2
        FROM    cart_table
        UNION ALL
        SELECT  id, item3
        FROM    cart_table
    )
)
GROUP BY combo

尽管我不喜欢嵌套的子查询...

答案 1 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id  INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,cart_no INT NOT NULL
,item VARCHAR(12) NOT NULL
,qty INT NOT NULL DEFAULT 1
,UNIQUE(cart_no,item)
);

INSERT INTO my_table VALUES
(1,1,'ball',1),
(2,1,'soap',1),
(3,2,'apple',1),
(4,2,'towel',1),
(5,2,'paper',1),
(6,3,'soap',1),
(7,3,'ball',1);

SELECT cart_no,GROUP_CONCAT(item ORDER BY item) combo FROM my_table GROUP BY cart_no;
+---------+-------------------+
| cart_no | combo             |
+---------+-------------------+
|       1 | ball,soap         |
|       2 | apple,paper,towel |
|       3 | ball,soap         |
+---------+-------------------+

SELECT combo, COUNT(0) total FROM
(
SELECT cart_no,GROUP_CONCAT(item ORDER BY item) combo FROM my_table GROUP BY cart_no
) x
GROUP BY combo;
+-------------------+-------+
| combo             | total |
+-------------------+-------+
| apple,paper,towel |     1 |
| ball,soap         |     2 |
+-------------------+-------+