计算字符串在类型为SET的行中出现的次数

时间:2010-02-19 14:52:03

标签: mysql count

我的数据库有四列:onetwothreefour每个列都有SET('a','b','c','d')类型。

我想知道每列中出现abcd的次数。

我想我可以做这样的事情

SELECT
(SELECT COUNT(*) FROM database as d WHERE d.a = 'one') AS one,
(SELECT COUNT(*) FROM database as d WHERE d.a = 'two') AS two,
(SELECT COUNT(*) FROM database as d WHERE d.a = 'three') AS three,
(SELECT COUNT(*) FROM database as d WHERE d.a = 'four') AS four
FROM database
LIMIT 1

我认识的四次会起作用。或者我可以获取整个结果并计算数组中的内容。

我可以以某种方式提高效率吗?

2 个答案:

答案 0 :(得分:1)

您可以使用casesum

在一个选择中合并多个计数
SELECT 
    sum(case when d.a = 'one' then 1 else 0 end) as SumAIsOne
,   sum(case when d.b = 'two' then 1 else 0 end) as SumBIsTwo
,   <other counts here>
FROM database

答案 1 :(得分:1)

select one,count(*) from db group by one
select two,count(*) from db group by two
etc