gpt4 book ai didi

MySQL COUNT() 和 FIND_IN_SET()

转载 作者:可可西里 更新时间:2023-11-01 09:01:12 25 4
gpt4 key购买 nike

是否可以对存储为逗号分隔值的数据执行计数?

例如我有两个表:

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


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

我想选择所有类别并对“猫”字段进行计数。

结果应该是这样的:

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;

最佳答案

有时,我们无法规范化数据,只需找到一个 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 |
+----------+------------+

关于MySQL COUNT() 和 FIND_IN_SET(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41927828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com