简体   繁体   English

MySQL COUNT()和FIND_IN_SET()

[英]MySQL COUNT() and FIND_IN_SET()

Is it possible to perform count with data stored as coma separated values? 是否可以使用存储为逗号分隔值的数据执行计数?

For example I have two tables: 例如,我有两个表:

Items:
=====================
id  name  cats
=====================
1   John  1,2
2   Peter 3
3   Jack  2


Categories:
===========================
id    name    
=========================== 
1     Animals
2     Vegetables
3     Fruits

I want to select all categories and perform count on "cats" field. 我想选择所有类别并对“cats”字段执行计数。

The result should look something like: 结果应该类似于:

Name          Counter
======================
Animals      1
Vegetables   2
Fruits       1

And here is my query: 这是我的查询:

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;

Time to time, we can't normalize data and it's fast to just find an SQL expression to manage this situation: 有时,我们无法规范化数据,只需找到一个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 |
+----------+------------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM