下面的查询正在从关系表中收集内容ID。它是确保我的结果有至少2个关键字匹配。
我的问题是,我也有一个“硬关键字”(假设ID 127),这意味着我需要确保硬关键字是必须包含的。我想我需要修改我的having
子句,但我不知道如何修改。
select * from `contents__keywords`
where `keyword_id` in (127, 162, 249, 567)
group by `content_id`
having count(distinct `keyword_id`) >= 2
order by `content_id`
desc
limit 4
您可以添加一个条件条件:
having count(distinct `keyword_id`) >= 2 and
sum(case when keyword_id = 127 then 1 else 0 end) > 0
如果您正在使用MySQL(如后勾提示的那样),您可以使用快捷方式:
having count(distinct `keyword_id`) >= 2 and
sum( keyword_id = 127 ) > 0
虽然你得到了一个很好的解决方案,但由于我已经准备好了,我在这里分享。
架构:
create table contents__keywords (content_id int ,keyword_id int);
insert into contents__keywords values(100,127);
insert into contents__keywords values(100,162);
insert into contents__keywords values(101,249);
insert into contents__keywords values(102,127);
查询:
select content_id,count(distinct keyword_id) keyword_id_count,sum(case when keyword_id=127 then 1 else 0 end)keyword_id102_count
from contents__keywords
where keyword_id in (127, 162, 249, 567)
group by content_id
having count(distinct keyword_id)>= 2 or keyword_id102_count>=1
order by content_id
desc
limit 4
输出: