在这里尝试了很多选项。我很抱歉 - 我无法从Db中获取正确的数据所以......
我有两张桌子。一个( books
)包含ID
book_id
52
49
1
49
1
49
另一个表格( authors
)包含ID的名称(即id 52 ='Dumas',49 ='Tolkien'等)
我想计算所有出现的结果并将结果返回为:
Author - Number of Occurences
----------------------------
Dumas | 12
-----------------------------
Tolkien | 8
etc
我可以使用此查询计算所有出现次数:
SELECT book_id,COUNT(*) as count FROM `books` GROUP BY `book_id` ORDER BY count DESC
效果不错但显然会将结果返回 ID:Occurrences ,而我需要名称:出现次数
答案 0 :(得分:3)
我认为作者表具有作者的ID,因为它是多对一的关系,其中一个作者可以与许多书籍相关。在这种情况下,您可以尝试此查询:
SELECT author_name, COUNT(*) as count
FROM `books`JOIN author on book_id = author_id
GROUP BY `author_name`
ORDER BY count DESC
为了避免同名作者的问题,你可以试试这个:
SELECT author_id, author_name, COUNT(*) as count
FROM `books`JOIN author on book_id = author_id
GROUP BY author_id, `author_name`
ORDER BY count DESC
答案 1 :(得分:-1)
使用SELECT
制作嵌套的GROUP BY
,然后将结果与原始表一起加入。以下查询将适用于以下架构:
<强>书强>
id author_id name
<强>作者强>
id name
**查询:**(同样为同名作者工作)
SELECT bb.name, _aa.count
FROM book AS aa
INNER JOIN (
SELECT book_id, COUNT(*) AS count
FROM book
GROUP BY book_id
) AS _aa
ON aa.book_id = _aa.book_id
INNER JOIN authors AS bb
ON aa.author_id = bb.id
ORDER BY _aa.count DESC;