看似简单的MYSQL查询
我的表格如下所示:
CREATE TABLE Author(
authorID INT PRIMARY KEY,
name VARCHAR(30)
);
CREATE TABLE book(
ISBN INT PRIMARY KEY,
title VARCHAR(30),
authorID INT,
inventory INT,
paperBack BOOLEAN,
fiction BOOLEAN,
FOREIGN KEY (authorID) REFERENCES Author(authorID)
);
我需要找出哪位作者写的书最多。
我正在混合使用以下内容。我想我在将它们拼凑在一起时遇到了麻烦...
SELECT authorID, count(*)
from book
group by authorID;
我不知道如何获取计数最高的单行,然后只获取该行的authorID。一旦我有了authorID,我就知道如何获取名字了。
Here is what my tables look like:
CREATE TABLE Author(
authorID INT PRIMARY KEY,
name VARCHAR(30)
);
CREATE TABLE book(
ISBN INT PRIMARY KEY,
title VARCHAR(30),
authorID INT,
inventory INT,
paperBack BOOLEAN,
fiction BOOLEAN,
FOREIGN KEY (authorID) REFERENCES Author(authorID)
);
I need to find out which author has written the most books.
I am working with a mixture of the following. I guess I am having trouble piecing it all together...
SELECT authorID, count(*)
from book
group by authorID;
I am not sure how to get the single row that has the highest count and then only get the authorID of that row. Once I have that authorID, I know how to get the name.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
Try this:
如果您想要的只是作者的 ID,请使用
ORDER BY
和LIMIT 1
正如其他人指出的那样。但是,如果您想要来自作者的其他字段,或者如果您对多个作者感兴趣(第二高计数、最低计数等),那么您应该考虑联接到派生表,像这样:会给出这样的结果集:
If all you want is the ID of the author, then use
ORDER BY
andLIMIT 1
as others have pointed out. However, if you're going to want other fields from Author, or if you are interested in multiple authors (second highest count, lowest count, etc), then you should consider joining to a derived table, like this:Would give a result set like this:
您不需要使用子查询,您可以执行如下操作:
SELECTauthorID FROM book GROUP BYauthorID ORDER BY COUNT(*) DESC LIMIT 1
这应该为您提供作者的authorID拥有最多的书籍。
You don't need to use a subquery, you can just do something like this:
SELECT authorID FROM book GROUP BY authorID ORDER BY COUNT(*) DESC LIMIT 1
this should give you the authorID of the author with the most books.