6

我有三张桌子:

author (columns: aut_id, aut_name)
book (columns: book_id, book_title)
authorbook (linking table, columns: aut_id, book_id)

每个作者都可以与一本书或多本书相关联。
每本书可以与一个或多个作者相关联。
我想按姓名和作者的确切人数来选择一本书。

表结构:

author    
aut_id    |   aut_name
1             Aname
2             Bname
3             Cname

book    
book_id    |  book_title (the titles are identical on purpose) 
1             Atitle
2             Atitle
3             Atitle

authorbook
aut_id    |   book_id 
1             1
1             2
2             2
1             3
2             3
3             3

这是我的代码(为了更好的说明,我省略了作者表):

SELECT authorbook.book_id 
FROM authorbook 
INNER JOIN book
ON authorbook.book_id = book.book_id
WHERE book_title='Atitle'
AND FIND_IN_SET (authorbook.aut_id,'1,2')
GROUP BY authorbook.book_id
HAVING (COUNT(authorbook.aut_id)=2)

问题:此代码不仅返回所需authorbook.book_id(2)的 TWO authorbook.aut_ids (1,2),还返回authorbook.book_id(3)THREE authorbook.aut_ids (1,2,3)

问题:我如何才能SELECT将一本书与该FIND_IN_SET条款中的作者完全关联(并且没有其他作者)?非常感谢你的帮助!

4

2 回答 2

2

尝试这个:

SELECT a.book_id
FROM authorbook a
INNER JOIN book b
ON a.book_id = b.book_id
WHERE b.book_title='Atitle'
  AND FIND_IN_SET (a.aut_id,'1,2')
GROUP BY a.book_id
HAVING COUNT(DISTINCT a.aut_id) = 2
   AND COUNT(DISTINCT a.aut_id) = (SELECT COUNT(DISTINCT a2.aut_id)
                                   FROM authorbook a2 
                                   WHERE a2.book_id = a.book_id);

SQL 小提琴演示

于 2012-12-11T11:37:16.457 回答
1

这应该工作

SELECT COUNT(aut_id) AS authors, book_id FROM (SELECT authorbook.*
FROM authorbook 
INNER JOIN book
ON authorbook.book_id = book.book_id
WHERE book_title='Atitle') AS t1 GROUP BY book_id HAVING authors='2'
于 2012-12-11T11:55:50.150 回答