MySQL:Select 如果另一列在交汇处有两个确定值,则与一列不同的值 table

MySQL: Select distinct values from one column if other column has two determined values in junction table

我有路口table:

CREATE TABLE `book_tags` (
  `id` int(11) NOT NULL,
  `book_id` int(11) DEFAULT NULL,
  `tag_id` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

具有类似

的值
INSERT INTO `book_tags` (`id`, `book_id`, `tag_id`) VALUES
(3, 20, 1),
(4, 20, 2),
(5, 21, 1),
(6, 22, 2),
(7, 24, 2);

如何找到同时具有两个或更多确定标签的书籍(book_id)? 例如,我怎样才能找到一本 tag_id=2 AND tag_id=1

的书

++++++++++++++++++++++++++++++++++++++++++

已更新:

通过 Whosebug 我找到了我的问题的答案。

对于 2 个必需的标签,解决方案将是:

SELECT * FROM `book_tags`
WHERE `tag_id` IN (1, 2)
GROUP BY book_id 
HAVING COUNT(*) = 2

对于我的特殊情况,此解决方案是 suitable,因为我知道在我的 table 中没有具有相同值对的行 book_id 和 tag_id.

感谢@Barbaros Özhan 和@scaisEdge 的帮助!

SELECT book_id FROM books_tags WHERE tag_id = 1 OR tag_id = 2?

SELECT book_id FROM books_tags WHERE tag_id IN (1, 2)

您可以尝试在搜索集中使用 tag_id 的子查询,并检查不同的计数 tag_id 是否符合搜索标签的数量

假设标签 1、2 那么

select book_id 
from (
  select book_id, tag_id 
  from  book_tags 
  where tag_id in  (1,2)
) t 
group by book_id
having count(distinct tag_id) = 2  


select book_id 
from (
  select book_id, tag_id 
  from  book_tags 
  where tag_id in  (1,2,5,7, 9, 11)
) t 
group by book_id
having count(distinct tag_id) = 5  

这将是一个使用 having 子句的弹性选项,如下所示,在 in 运算符列表 (in (1,2,3,...)) 之后添加更多 tag_id 以进行过滤:

select `book_id` 
  from `book_tags` 
 where `tag_id` in (1,2,3) 
 group by `book_id` 
having count(`tag_id`) = count(distinct `tag_id`)
   and count(distinct `tag_id`) > count(distinct `book_id`);

Demo