簡體   English   中英

MySQL根據特定的字段值和行數選擇多行

[英]MySQL SELECT multiple rows based on specific field value and number of rows

我有三張桌子:

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)

問題:此代碼不僅返回帶有TWO authorbook.aut_ids (1,2)的所需authorbook.book_id(2) ,還authorbook.book_id(3)帶有THREE authorbook.aut_ids (1,2,3)authorbook.book_id(3) authorbook.aut_ids (1,2,3)

問題:如何在FIND_IN_SET子句中SELECT與作者完全關聯的書籍(並且沒有其他作者)? 非常感謝你的幫助!

試試這個:

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小提琴演示

這應該工作

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM