如何确保结果至少包含一个 ID?

How to make sure results will contain at least one ID?

以下查询正在从关系 table 中收集内容 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

输出:

content_id keyword_id_count keyword_id102_count
102 1 1
100 2 1

db<>fiddle here