SQL查询麻烦:“无效使用组功能”

时间:2013-02-09 19:41:30

标签: mysql join group-by

注意:我知道查询不完整,我试图将它拼凑在一起。我此时遇到了错误

基本上,我收到MySQL错误

  

无效使用群组功能

我无法弄明白为什么。

这是我正在查询的数据库的图表:

diagram

问题是:

“显示为已发布两本以上图书的发布商发布的出版商名称和图书数量。记录应按降序发布的图书数量排序,然后按出版商名称升序排序。您的输出应该匹配下面给出的显示(包括列标题)。“

输出看起来像:

output

这是我正在尝试的查询:

select publisher.name as "Publisher Name", count(book.isbn)
from publisher as "Book Count"
join book using (publisherID)
where count(book.isbn) > 2
group by publisher.name;

4 个答案:

答案 0 :(得分:1)

尝试

SELECT MIN(p.name) AS `Publisher Name`, COUNT(b.isbn) AS `Book Count`
  FROM publisher AS p INNER JOIN 
       book      AS b ON p.PublisherID = b.PublisherID
GROUP BY p.publisherID
HAVING COUNT(b.isbn) > 2

这是sqlfiddle

答案 1 :(得分:0)

问题出在您的from声明中。正确的语法是:

select publisher.name as "Publisher Name", count(book.isbn)  as "Book Count"
from publisher join book
     using (publisherID)
group by publisher.name;

有计数(book.isbn)> 2

您为publisher表提供了Book Count的别名,而非计数。

答案 2 :(得分:0)

2个问题:

  1. 您已将别名添加到表中,而不是列。

  2. 您无法在COUNT条件下使用WHERE。您需要使用HAVING

  3. 尝试以下方法:

    SELECT
        publisher.name as `Publisher Name`,
        COUNT(book.isbn) as `Book Count`
    FROM
        publisher 
    JOIN
        book USING (publisherID)
    GROUP BY
        publisher.name
    HAVING
        `Book Count` > 2
    

答案 3 :(得分:0)

您无法在SELECT中使用COUNT。 尝试在小组中使用HAVING条件。