多个标签搜索查询不起作用

时间:2018-07-05 06:31:13

标签: mysql tags

我有一个查询,可以通过多个标签搜索数据,我从问题Multiple tags search query中得到了这个想法。我有3张桌子,例如books(id,title ....)。标签(id,名称),books_tag(id,book_id,tag_id)。因此,我使用查询通过标签选择书籍,但未给出任何结果。

Books Table

id : title
 1 : maths
 2 : science
 3 : HP

标签表

id : name
 1 : a
 2 : b
 3 : c

Boook_tag表

id : book_id : tag_id
 1 :    1    :   2
 2 :    1    :   3 
 3 :    2    :   1
 4 :    3    :   1
 5 :    3    :   2

因此,如果我搜索书籍标签c,则结果应为book_id 1(数学),或者按c和a搜索,结果应为book_id 1,2,3(数学,科学,惠普)

这是我的查询

SELECT books_tag.book_id, books_pre.title
FROM books_tag
JOIN books_pre ON books_tag.book_id = books_pre.id
JOIN tags ON books_tag.tag_id = tags.id
WHERE tags.name IN ('a', 'd')
GROUP BY books_tag.book_id
HAVING COUNT(books_tag.tag_id) = 2

3 个答案:

答案 0 :(得分:0)

您应该使用count(distinct books_tag.tag_id)

SELECT books_tag.book_id, books_pre.title
FROM books_tag
JOIN books_pre ON books_tag.book_id = books_pre.id
JOIN tags ON books_tag.tag_id = tags.id
WHERE tags.name IN ('a', 'd')
GROUP BY books_tag.book_id
HAVING COUNT(distinct books_tag.tag_id) = 2

答案 1 :(得分:0)

您要尝试的查询是针对AND条件的,例如获取带有AND标签d的那些书。根据您的问题,您不需要该条件,只需删除带有and子句的组即可,会没事的

SELECT DISTINCT b.*
FROM books_pre b
JOIN books_tag bt ON bt.book_id = b.id
JOIN tags t ON bt.tag_id = t.id
WHERE t.name IN ('a', 'b')

Demo

答案 2 :(得分:0)

尝试以下简短查询:

样本数据:

create table Books(id int, title varchar(10));
insert into Books values
(1, 'maths'),
(2, 'science'),
(3, 'HP');
create table Tag(id int, name char(1));
insert into Tag values                            
(1, 'a'),
(2, 'b'),
(3, 'c');
create table Book_tag(id int, book_id int, tag_id int);
insert into Book_tag values
(1, 1, 2),
(2, 1, 3),
(3, 2, 1),
(4, 3, 1),
(5, 3, 2);

T-SQL:

select distinct book_id from Book_tag bt
where exists(select 1 from Tag
             where id = bt.tag_id
                   and name in ('c', 'a'));

name in (...)部分中,您指定了要搜索的标签。

相关问题