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

时间:2019-07-30 12:45:05

标签: mysql sql select group-by 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寻求帮助!

3 个答案:

答案 0 :(得分: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  

答案 1 :(得分:1)

使用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`); 进行过滤之后, / p>

copy()

Demo

答案 2 :(得分:0)

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)