-- [params]
-- string_list :first_list_of_keywords
-- null string_list :second_list_of_keywords
WITH FirstFilter AS (
SELECT *
FROM posts
WHERE EXISTS (
SELECT 1
FROM UNNEST(ARRAY[:first_list_of_keywords]) AS s(word)
WHERE POSITION(LOWER(s.word) IN LOWER(posts.raw)) > 0
)
), SecondFilter AS (
SELECT *
FROM posts
WHERE NOT EXISTS (
-- 确保帖子文本中没有缺失的关键字
SELECT 1
FROM UNNEST(ARRAY[:second_list_of_keywords]) AS t(word)
WHERE POSITION(LOWER(t.word) IN LOWER(posts.raw)) = 0
)
)
SELECT p.*
FROM posts p
INNER JOIN FirstFilter f ON p.id = f.id
INNER JOIN SecondFilter s ON p.id = s.id
只需扩展 WHERE 子句,即可根据 topics 表搜索 topic_id,该表将具有 category_id 列。
-- [params]
-- int :category_id
-- string_list :first_list_of_keywords
-- null string_list :second_list_of_keywords
WITH FirstFilter AS (
SELECT *
FROM posts
WHERE topic_id IN (
SELECT id FROM topics WHERE category_id = :category_id
) AND EXISTS (
SELECT 1
FROM UNNEST(ARRAY[:first_list_of_keywords]) AS s(word)
WHERE POSITION(LOWER(s.word) IN LOWER(posts.raw)) > 0
)
), SecondFilter AS (
SELECT *
FROM posts
WHERE NOT EXISTS (
-- 确保帖子文本中没有缺失的关键字
SELECT 1
FROM UNNEST(ARRAY[:second_list_of_keywords]) AS t(word)
WHERE POSITION(LOWER(t.word) IN LOWER(posts.raw)) = 0
)
)
SELECT p.*
FROM posts p
INNER JOIN FirstFilter f ON p.id = f.id
INNER JOIN SecondFilter s ON p.id = s.id