[英]How to select distinct values from one column from on table and entire other table?
[英]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.