Tagged articles selection - more complex case (tags defined by logical expression)

I know, its simple to select all articles with at least on of tags "14 OR 16 OR 17" ... (only simple disjunction) ...

SELECT _article_id from articles_x_tags
WHERE _id_tag in (14,16,17)
GROUP BY _id_article

How to do same thing (quick way, and only one sql query) when i have to list articles with these tags "(14 OR 16) AND (17 OR 18) AND NOT(13)" ? ... (negation, conjunction, disjunction) ... Thank you for your help and ideas!


SAMPLE TABLE: articles_x_tags

╔════════════════╦════════════════════╗
║ _id_tag(int11) ║ _id_article(int11) ║
╠════════════════╬════════════════════╣
║ 14             ║ 2566               ║
║ 17             ║ 2566               ║
║ 13             ║ 2566               ║
║ 14             ║ 2567               ║
║ 17             ║ 2567               ║
║ 14             ║ 2568               ║
║ ...            ║ ... milion records ║
╚════════════════╩════════════════════╝

Upvotes: 1

Views: 20

Answers (1)

fthiella
fthiella

Reputation: 49069

I would use a query like this:

SELECT
  id_article
FROM
  articles_x_tags
WHERE
  id_tag IN (14, 16, 17, 18, 13)
GROUP BY
  id_article
HAVING
  SUM(id_tag=14 OR id_tag=16)>0
  AND SUM(id_tag=17 OR id_tag=18)>0
  AND SUM(id_tag=13)=0

Upvotes: 1

Related Questions