6

我对多表查询有一点问题。(RDBMS:访问)

这是数据库模式:(此查询中仅使用 S_Cards、Books、Authors、Student 表)S_Cards 是 Student 图书订单(在图书馆中)。

数据库方案

查询:选择学生中最受欢迎的作者以及该作者在图书馆订购的书籍数量。

虽然我可以在一个查询中获得这样的订单+作者列表:

SELECT 
    Students.FirstName & " " & Students.LastName AS [Student], 
    Books.Name AS [Book], Authors.FirstName & " " & Authors.LastName AS [Author]
FROM 
    Students, 
    Books, 
    S_Cards, 
    Authors
WHERE 
    S_Cards.ID_Student = Students.ID 
AND S_Cards.ID_Book = Books.ID 
AND Books.ID_Author = Authors.ID
ORDER BY Authors.LastName

结果(对不起,它是俄语):

查询结果

我想不通,为什么我不能像这样 COUNT 和 GROUP BY:

SELECT 
    Students.FirstName & " " & Students.LastName AS [Student], 
    Books.Name AS [Book], 
    COUNT(Authors.FirstName & " " & Authors.LastName) AS [Number of books]
FROM Students, Books, S_Cards, Authors
WHERE 
    S_Cards.ID_Student = Students.ID 
AND S_Cards.ID_Book = Books.ID 
AND Books.ID_Author = Authors.ID
GROUP BY 3

我收到一条错误消息,“Authors.FirstName & " " & Authors.LastName' 不是静态函数或组的一部分。

问题:

  1. 有没有办法在没有 JOIN 的情况下仅通过 GROUP BY、SELECT、UNION 以及如何执行此查询?
  2. 我的第二个查询有什么问题?
4

3 回答 3

1

解决方案(从有问题的旧版本中提取):

SELECT TOP 1 Author, COUNT(Book) AS [Number of books] FROM
(
    SELECT 
        Students.FirstName & " " & Students.LastName AS [Student], 
        Books.Name AS [Book], 
        Authors.FirstName & " " & Authors.LastName AS [Author]
    FROM 
        Students, 
        Books, 
        S_Cards, 
        Authors
    WHERE 
        S_Cards.ID_Student = Students.ID AND
        S_Cards.ID_Book = Books.ID AND
        Books.ID_Author = Authors.ID
    ORDER BY Authors.LastName
)
GROUP BY Author
ORDER BY 2 DESC
于 2015-09-22T02:03:36.280 回答
0

您必须 GROUP BY 不属于聚合函数的任何内容:

SELECT 
    Students.FirstName & " " & Students.LastName AS [Student], 
    Books.Name AS [Book], 
    COUNT(Authors.FirstName & " " & Authors.LastName) AS [Number of books]
FROM Students, Books, S_Cards, Authors
WHERE 
    S_Cards.ID_Student = Students.ID 
AND S_Cards.ID_Book = Books.ID 
AND Books.ID_Author = Authors.ID
GROUP BY Students.FirstName & " " & Students.LastName, 
    Books.Name AS [Book]

我建议您开始使用显式而不是隐式连接。在大多数情况下,MS Access 有更好的选择。

<...>
FROM Students
INNER JOIN S_Cards
ON Students.ID = S_Cards.ID_Student

或者

<...>
FROM Students
LEFT JOIN S_Cards
ON Students.ID = S_Cards.ID_Student

查询设计窗口将允许您使用正确的语法构建您的 JOIN。只需将连接字段从一个表拖放到下一个表,然后选择您需要的连接类型。

于 2012-09-16T22:09:39.020 回答
0

SQL Server 中的字符串连接运算符+不是&. 此外,您应该按不是聚合函数的事物进行分组。

SELECT Students.FirstName + ' ' + Students.LastName AS [Student]
     , Books.Name AS [Book]
     , COUNT(Authors.FirstName + ' ' + Authors.LastName) AS [Number of books]
  FROM Students
  JOIN S_Cards
    ON S_Cards.ID_Student = Students.ID
  JOIN BOOKS
    ON S_Cards.ID_Book = Books.ID 
  JOIN Authors
    ON Books.ID_Author = Authors.ID
 GROUP BY Students.FirstName + ' ' + Students.LastName
        , Books.Name

请注意,我已将您的查询更改为标准的 ANSI 连接语法,这使得错误更难产生并且更易于阅读。

想了想,你的计数似乎有些奇怪。不是书的数量COUNT(Books.ID)吗?

于 2012-09-16T13:55:19.317 回答