指定カテゴリIDで特定のパラメータに一致する全投稿の取得

サイト内の特定のキーワードを含むすべての投稿を取得するSQLクエリを開発しましたが、投稿を特定のカテゴリIDに制限したいと思います。「posts」テーブルにはcategory_idフィールドがない(ように見える)場合、その方法を知っている人はいますか?以下は私のクエリです(実行済みで問題なく動作しますが、すべての投稿から取得しており、1つのカテゴリからの投稿のみが必要です)。

-- [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 (
        -- Ensure there is NO missing keyword in the post text
        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句を拡張して、category_id列を持つtopicsテーブルに対してtopic_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 (
        -- Ensure there is NO missing keyword in the post text
        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
「いいね!」 4

ありがとうございます、これがうまくいきました。

「いいね!」 1

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.