我在书籍和作者之间有很多联系。
如何获得作者不止一个的所有书籍? (在下面的示例数据库中,该值为0)
books表:
+--------+------------------+
| BookId | Book |
+--------+------------------+
| 1 | Wizard of Oz |
| 2 | Huckleberry Finn |
+--------+------------------+
作者表:
+----------+------------------+
| AuthorId | Author |
+----------+------------------+
| 1 | Mark Twain |
| 2 | Lyman Frank Baum |
+----------+------------------+
连接表:
+--------+----------+
| BookId | AuthorId |
+--------+----------+
| 1 | 2 |
| 2 | 1 |
+--------+----------+
答案 0 :(得分:3)
您可以使用分组计数
select books.* from books
inner join junction on books.id = junction.bookid
group by bookId
having count(distinct AuthorId ) > 1
答案 1 :(得分:2)
使用distinct
count()
select * from books where BookId
in ( select BookId from junction_table
group by BookId
having count(distinct AuthorId)>=2
)
答案 2 :(得分:1)
此处可以使用CTE(公用表表达式)(请参阅https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql)。
首先为CTE命名,指定内部查询,即获取拥有多个作者的所有图书名称,然后使用外部查询提取CTE返回的图书的详细信息。优点是CTE具有模块化和可读性。
WITH CTE
AS
(
SELECT Bookid,COUNT(DISTINCT AuthorID) AS No_Of_Authors
FROM
Junction
HAVING COUNT(DISTINCT AuthorID)>1
)
SELECT * FROM CTE C JOIN Book B
ON
C.Bookid=B.Bookid
答案 3 :(得分:0)
请尝试以下操作是否达到您的期望:
SELECT *
FROM
(
SELECT b, COUNT(b) as authors
FROM j
GROUP BY 1
) cnt
WHERE cnt.authors > 1