是否可以使用存储为逗号分隔值的数据执行计数?
例如,我有两个表:
Items:
=====================
id name cats
=====================
1 John 1,2
2 Peter 3
3 Jack 2
Categories:
===========================
id name
===========================
1 Animals
2 Vegetables
3 Fruits
我想选择所有类别并对'#34;猫"字段。
结果应该类似于:
Name Counter
======================
Animals 1
Vegetables 2
Fruits 1
这是我的疑问:
SELECT
c.id,
c.name,
(SELECT
COUNT(i.id)
FROM
Items AS i
WHERE FIND_IN_SET(c.id, i.cats)) AS total
FROM
categories AS c;
答案 0 :(得分:0)
不时,我们无法规范化数据,只需找到一个SQL表达式来管理这种情况就快了:
select count(*), c.name from items as i,category as c where find_in_set( c.id , i.cats ) !=0 group by c.name;
+----------+------------+
| count(*) | name |
+----------+------------+
| 1 | Animals |
| 1 | Fruits |
| 2 | Vegetables |
+----------+------------+