繁体   English   中英

MySQL:如果另一列在连接表中有两个确定的值,则从一列中选择不同的值

[英]MySQL: Select distinct values from one column if other column has two determined values in junction 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 的书

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

更新

查看stackoverflow,我找到了我的问题的答案。

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

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

此解决方案适用于我的特定情况,因为我知道在我的表中没有具有相同 book_id 和 tag_id 值对的行。

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

您可以尝试在搜索集中使用 tag_id 的子查询,并检查 count distinct tag_id quae 到搜索标签的数量

假设标签 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  

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

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`);

演示

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM