使用 SQL (mySQL) 在类似 csv 的列中执行 group by 语句的最佳方法是什么?
Table Products Color
+-------------+--------------+
| Product Id | Color |
+-------------+--------------+
| 120 | Red, Blue |
| 121 | Green, Black |
| 122 | Red, Black |
+-------------+--------------+
从上表中,我需要计算某种颜色出现的次数并返回如下内容:
+-------------+-------+
| Color | Count |
+-------------+-------+
| Red | 2 |
| Blue | 1 |
| Green | 1 |
| Black | 2 |
+-------------+-------+
是否可以在不规范数据库的情况下做到这一点?
最佳答案
如果您无法更改表结构,但可以创建一个列出所有颜色的表,则可以使用以下查询:
SELECT Colors.Color, Count(*)
FROM
Products INNER JOIN Colors
ON FIND_IN_SET(Colors.Color, REPLACE(Products.Color, ' ', ''))>0
GROUP BY
Colors.Color
查看它的工作情况 here 。请注意,它无法优化,因为它无法在索引上使用。
关于Mysql 在 CSV 字段中进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18601915/