优化/简化此SQL查询

时间:2016-06-21 00:37:33

标签: mysql optimization

我有这个查询并且它有效,但我知道这可以简化:

SELECT class, COUNT(class), publisher FROM books WHERE publisher = 'Company ABC' GROUP BY class
UNION
SELECT class, COUNT(class), publisher FROM books WHERE publisher = 'Company DEF' GROUP BY class
UNION
SELECT class, COUNT(class), publisher FROM books WHERE publisher = 'Company GHI' GROUP BY class
UNION
SELECT class, COUNT(class), publisher FROM books WHERE publisher = 'Company JKL' GROUP BY class
UNION
SELECT class, COUNT(class), publisher FROM books WHERE publisher = 'Company MNO' GROUP BY class;

它也是硬编码但我真的希望查询在表中寻找不同的公司:

SELECT DISTINCT publisher FROM books;

结果:

publisher
Company ABC
Company DEF
Company GHI
Company JKL
Company MNO

2 个答案:

答案 0 :(得分:0)

使用以下查询

SELECT class, COUNT(class), publisher 
FROM books 
GROUP BY class,publisher 

答案 1 :(得分:0)

您的查询格式错误。您的DBMS应该拒绝它并出现错误。你说它"工作",所以我猜它做你想做的事,但我不确定我能告诉你如何改进它。

基本问题是

SELECT class,
       COUNT(class) as N,
       publisher
FROM books
GROUP BY class

使用聚合(COUNT)时,GROUP BY子句必须包含SELECT子句中的每个非聚合。在你的情况下,它必须说

GROUP BY class, publisher

如果您只说GROUP BY class,那么该计数代表什么?我希望DBMS有点聪明":在您的查询中,publisher是单个值,因此COUNT是非NULL {{1}的数量该发布者的每个类的值。

相当于

class

如果这样做你想要的,那肯定是一种改进。它是标准的SQL,几乎肯定会执行得更快。