I have 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;
with values like
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);
How can I find the books (book_id) which have two or more determined tags at the same time? For example, how can I find a book which have tag_id=2 AND tag_id=1
+++++++++++++++++++++++++++++++++++++++
UPDATED :
Looking through stackoverflow I've found the answer on my question.
For 2 required tags the solution will be:
SELECT * FROM `book_tags`
WHERE `tag_id` IN (1, 2)
GROUP BY book_id
HAVING COUNT(*) = 2
This solution is suitable for my particular case, since I know that in my table there is no rows with the same pair of values of book_id and tag_id.
Thank you @Barbaros Özhan and @scaisEdge for help!
You could try using a subquery for tag_id in you searched set and the check for count distinct tag_id quae to the number of your searched tag
Assuming tag 1, 2 then
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
It would be an elastic option using a having
clause as in the following way as you add after in
operator's list( in (1,2,3,...)
) more tag_id
to filter:
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
?
Or
SELECT book_id FROM books_tags WHERE tag_id IN (1, 2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.