Alle Beiträge für eine bestimmte Kategorien-ID abrufen, die bestimmten Parametern entsprechen

Ich habe eine SQL-Abfrage entwickelt, die alle Beiträge auf meiner Website abruft, die bestimmte Schlüsselwörter enthalten. Ich möchte die Beiträge jedoch auf eine bestimmte Kategorie-ID beschränken. Weiß jemand, wie das geht, da die Kategorie-ID (scheinbar) kein Feld in der Tabelle „posts“ ist? Hier ist meine Abfrage (die ich ausgeführt habe und die einwandfrei funktioniert, aber alle Beiträge abruft und ich nur Beiträge aus einer Kategorie möchte):

-- [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 (
        -- Sicherstellen, dass KEIN Schlüsselwort im Beitragstext fehlt
        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

Ich musste nur die WHERE-Klausel erweitern, um die topic_id gegen die topics-Tabelle zu suchen, die die Spalte category_id haben wird.

-- [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 (
        -- Stellen Sie sicher, dass kein Schlüsselwort im Post-Text fehlt
        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 „Gefällt mir“

Vielen Dank, das hat funktioniert.

1 „Gefällt mir“

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