Ottenere tutti i post per un dato ID di categoria che corrispondono a determinati parametri

Ho sviluppato una query SQL che ottiene tutti i post del mio sito che contengono determinate parole chiave, ma vorrei limitare i post a un ID di categoria specifico. Qualcuno sa come fare, dato che (apparentemente) category_id non è uno dei campi della tabella “posts”? Ecco la mia query (che ho eseguito e funziona bene, ma estrae da TUTTI i post e io voglio solo post da una categoria):

-- [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 (
        -- Assicurati che NON ci sia alcuna parola chiave mancante nel testo del post
        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

Era sufficiente estendere la clausola WHERE per cercare il topic_id nella tabella topics, che avrà la colonna 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 (
        -- Assicurati che NON ci sia alcuna parola chiave mancante nel testo del post
        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 Mi Piace

Grazie, questo ha funzionato.

1 Mi Piace

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