用SQL获取2位或更多作者的书籍

时间:2019-11-03 04:44:35

标签: sql join select count

所以我遇到了一个问题,我要买的作者多于两个的书。我是T-SQL的新手,所以我还不太了解。.

我的桌子看起来像这样

书桌:

     BOOK
---------------
book_id | title
---------------
   1    |   A
   2    |   B

作者表:

     AUTHOR
----------------
author_id | name
----------------
     1    | Nick
     2    | Clem
     3    | John

Book-Author表:

  BOOK_AUTHOR
--------------------
book_id |  author_id
--------------------
   1    |     1
   1    |     2
   2    |     3

因此,正如您所看到的,我想要的预期输出是:


 Author_id |  title  |       author_name
------------------------------------------
    1    |    A    | Nick
    2    |    A    | Clem

这是我正在执行的SQL查询:

SELECT a.Id, a.name, b.title, count(ba.idBook)
FROM BookAuthors as ba
JOIN Author as a
ON ba.IdAuthor = a.Id
JOIN book as b
ON ba.idBook = b.id
GROUP BY a.Id, a.name, b.title
HAVING count(ba.idBook) > 1

预先感谢大家!

2 个答案:

答案 0 :(得分:2)

您可以使用子查询,该子查询将查找所有具有两个以上作者的书籍ID:

SELECT c.book_id
  FROM book_author c
  GROUP BY c.book_id
  HAVING count(c.book_id) >= 2

...,然后在您的主查询中使用它,以从联接的表中获取所有作者和书籍,其书籍ID出现在子查询中:

SELECT ba.author_id, a.name AS author_name, b.title
FROM 
    book_author ba JOIN book b ON ba.book_id = b.book_id
    JOIN author a ON ba.author_id = a.author_id
WHERE
    b.book_id IN (SELECT c.book_id
                    FROM book_author c
                    GROUP BY c.book_id
                    HAVING count(c.book_id) >= 2);

答案 1 :(得分:0)

您希望本书的作者超过两名。您的查询已结束,但您想排除特定的作者信息:

SELECT b.Id, b.title, COUNT(*) as num_authors
FROM BookAuthors ba JOIN
     book b
     ON ba.idBook = b.id
GROUP BY b.id, b.title
HAVING COUNT(*) > 2;

这个问题似乎并没有要求您列出作者。如果是这样,一种方便的方法将是STRING_AGG()

SELECT b.Id, b.title, COUNT(*) as num_authors,
       STRING_AGG(author_name, ', ') as authors
FROM BookAuthors ba JOIN
     book b
     ON ba.idBook = b.id
GROUP BY b.id, b.title
HAVING COUNT(*) > 2;

STRING_AGG()是SQL Server的较新功能,因此在您使用的版本中可能不可用。