我有一个 MySQL 表
id | string
------------------------------
1 | one, two, three
2 | two, three, five
3 | one, three, four
4 | three, five
5 | one, two, three
6 | two, three, five
7 | one, three, four
8 | one, three, five
9 | two, three, four, five
10 | one, two, three, five
我想获取string
列中包含子字符串two
的元素的比例。我可以轻松执行两个查询并手动划分它们:
SELECT COUNT(*) FROM `table` WHERE `string` LIKE '%three%'
然后除以
SELECT COUNT(*) FROM `table`
但是我怎样才能只用一个查询来执行此操作呢?
最佳答案
您可以使用 SUM 与 IF 来在括号内给出 1 或 0:-
SELECT SUM(IF(`string` LIKE '%three%', 1, 0))/COUNT(*)
FROM `table`
关于mysql - 如何在一个查询中执行两次 COUNT(*) 获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24822657/