[英]Count number of Rows with the same value in a Column
I have these two entity with their attributes:我有这两个实体及其属性:
book - book_id, book_name, author_id, editor_id, subject_id, isbn
book - book_id、book_name、author_id、editor_id、subject_id、isbn
author - author_id, fn, ln
作者 - author_id, fn, ln
I have to query the author with the most number of rows here's the attributes and entity:我必须用最多的行数查询作者,这里是属性和实体:
| book_id | book_name | author_id | editor_id | isbn | -------------------------------------------------------------- | 1 | Book1 Title | Author1 | Editor1 | 8000-9000 | | 2 | Book2 Title | Author2 | Editor1 | 8000-9001 | | 1 | Book1 Title | Author1 | Editor1 | 8000-9002 | | 3 | Book2 Title | Author2 | Editor1 | 8000-9003 |
| author_id | fn | ln | --------------------------------- | 1 | name1 | lname1 | | 2 | name2 | lname2 | | 3 | name3 | lname3 |
and here is my code:这是我的代码:
SELECT author.author_id, author.fn, author.ln, COUNT(DISTINCT book.editor_id) as num
FROM `editor`, `book`
GROUP BY `editor_id`
LIMIT 0,1
but off-course i don't get what I want.但当然我没有得到我想要的。 The output must be:
输出必须是:
| author_id | fn | ln | --------------------------------- | 1 | name1 | lname1 |
since the "author_id = 1" has 2 entries on books.因为“author_id = 1”在书籍上有 2 个条目。
Try this one but please take note that I converted the author_id
from varchar
to int
):试试这个,但请注意,我将
author_id
从varchar
转换为int
):
SELECT book_count,a.author_id,a.fn, a.ln
FROM author a
JOIN
(
SELECT c.author_id,COUNT(*) book_count FROM book c
GROUP BY c.author_id
) b
ON a.author_id = b.author_id
ORDER BY book_count DESC LIMIT 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.