假设我有一个包含 author_name、book_name 和 page_count 列的书籍表。
我如何编写 SQL 来找到一个作者写了多本书并且同一作者的至少两本书具有不同页数的实例?
我设法通过以下方式检索了包含多本书的作者列表
SELECT author_name FROM books
GROUP BY author_name
HAVING COUNT(book_name) > 1
我相信这样做,但是我如何检查每本书以比较它们的页数?
假设我有一个包含 author_name、book_name 和 page_count 列的书籍表。
我如何编写 SQL 来找到一个作者写了多本书并且同一作者的至少两本书具有不同页数的实例?
我设法通过以下方式检索了包含多本书的作者列表
SELECT author_name FROM books
GROUP BY author_name
HAVING COUNT(book_name) > 1
我相信这样做,但是我如何检查每本书以比较它们的页数?
你可以试试这个:
SELECT author_name
FROM books
GROUP BY author_name
HAVING COUNT(distinct page_count) > 1
这不会查找多本书,因为如果有多个页数,那么就会有多本书。
出于性能原因,我通常使用这样的东西:
SELECT author_name
FROM books
GROUP BY author_name
HAVING min(page_count) <> max(page_count)
通常,count(distinct)
比仅仅做一个min()
and更昂贵max()
。
如果您想获取所有书籍的列表,请返回此列表。这是一个使用in
子查询的示例:
select b.*
from books b
where b.author in (SELECT author_name
FROM books
GROUP BY author_name
HAVING min(page_count) <> max(page_count)
)
这应该这样做:
SELECT author_name FROM (
SELECT author_name, page_count FROM books
GROUP BY author_name, page_count
)
GROUP BY author_name
HAVING COUNT(*) > 1
试试这个。它应该工作
Select Distinct author_name From books b
Where Exists (Select * From test
Where author_name = b.author_name
Having count(*) > 1)
And Exists (Select * books test b1 Join books b2
On b1.author_name = b2.author_name
And b1.book_name<> b2.book_name
And b1.page_count <> b2.page_count
Where b1.author_name = b.author_name )
要查看完整的书籍列表,只需在外部查询中包含 book_name 并消除不同的...
Select author_name, book_name From books b
Where Exists (Select * From test
Where author_name = b.author_name
Having count(*) > 1)
And Exists (Select * books test b1 Join books b2
On b1.author_name = b2.author_name
And b1.book_name<> b2.book_name
And b1.page_count <> b2.page_count
Where b1.author_name = b.author_name )