我的数据库有四列:one
,two
,three
和four
每个列都有SET('a','b','c','d')
类型。
我想知道每列中出现a
,b
,c
和d
的次数。
我想我可以做这样的事情
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
我认识的四次会起作用。或者我可以获取整个结果并计算数组中的内容。
我可以以某种方式提高效率吗?
答案 0 :(得分:1)
您可以使用case
和sum
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