MySQL 根据特定字段值和行数选择多行
Posted
技术标签:
【中文标题】MySQL 根据特定字段值和行数选择多行【英文标题】:MySQL SELECT multiple rows based on specific field value and number of rows 【发布时间】:2012-11-28 22:43:08 【问题描述】:我有三张桌子:
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)
和两个authorbook.aut_ids (1,2)
,还返回authorbook.book_id(3)
和三个authorbook.aut_ids (1,2,3)
。
问题:我如何SELECT
与FIND_IN_SET
子句中的作者(且没有其他作者)完全相关联的书?
非常感谢你的帮助!
【问题讨论】:
【参考方案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'
【讨论】:
非常感谢!这行得通。但是,当我添加另一本书 (book_id = 4, aut_ids = 1,3) 时,此查询也会返回新书(所以我得到两个结果 - book_id 2 AND 4 - 而不是所需的一个 (book_id 2))。有没有办法只得到一个结果,其中作者的数量是 2 并且两个作者是指定的作者(1,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 Fiddle Demo
【讨论】:
以上是关于MySQL 根据特定字段值和行数选择多行的主要内容,如果未能解决你的问题,请参考以下文章
(MySQL)按字段分组并选择 COUNT(field) 和分组行数