我的表中有不同类别的数据。我想计算每个类别中的项目。每个部分包含两个以上的类别。
如何优化此查询?
SELECT s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12
FROM (
(SELECT count(category) as s1 FROM `category_data` WHERE `type` = '2' and category IN ('2','3','4','5','6','7')) AS t1,
(SELECT count(category) as s2 FROM `category_data` WHERE `type` = '2' and category IN ('8','9','10','11','12')) AS t2,
(SELECT count(category) as s3 FROM `category_data` WHERE `type` = '2' and category IN ('13','14','15','16','17')) AS t3,
(SELECT count(category) as s4 FROM `category_data` WHERE `type` = '2' and category IN ('18','19','20','21','22')) AS t4,
(SELECT count(category) as s5 FROM `category_data` WHERE `type` = '2' and category IN ('23','24','25','26','27')) AS t5,
(SELECT count(category) as s6 FROM `category_data` WHERE `type` = '2' and category IN ('28','29','30','31','32')) AS t6,
(SELECT count(category) as s7 FROM `category_data` WHERE `type` = '2' and category IN ('33','34','35','36','37')) AS t7,
(SELECT count(category) as s8 FROM `category_data` WHERE `type` = '2' and category IN ('38','39','40','41','42')) AS t8,
(SELECT count(category) as s9 FROM `category_data` WHERE `type` = '2' and category IN ('43','44','45','46','47')) AS t9,
(SELECT count(category) as s10 FROM `category_data` WHERE `type` = '2' and category IN ('48','49','50','51','52')) AS t10,
(SELECT count(category) as s11 FROM `category_data` WHERE `type` = '2' and category IN ('53','54','55','56','57')) AS t11,
(SELECT count(category) as s12 FROM `category_data` WHERE `type` = '2' and category >= ('58')) AS t12
)
答案 0 :(得分:1)
SELECT
SUM(category IN ('2','3','4','5','6','7')) AS s1,
...
SUM(category >= ('58')) AS s12
FROM
`category_data`
WHERE `type` = '2'
您可以多次阅读该表,而不是多次阅读该表
我使用SUM()
而不是count,因为它中的布尔表达式等于true
或false
,1
或0
,这基本上与计数。
答案 1 :(得分:0)
您可以使用大小写来减少表引用的数量:
SELECT count(case when type = 2 and category IN ('2','3','4','5','6','7') then 1 end)
, count(case when type = 2 and category IN ('8','9','10','11','12') then 1 end)
...
FROM `category_data
`
答案 2 :(得分:-1)
我认为你应该在表格上使用分区" category_data"按类别列。看看http://dev.mysql.com/doc/refman/5.7/en/partitioning-types.html。您可以通过LIST对其进行分区以进行参考。 http://dev.mysql.com/doc/refman/5.7/en/partitioning-list.html