标记文章选择 - 更复杂的情况(标记由逻辑表达式定义)

时间:2014-09-17 09:30:49

标签: mysql sql select tags

我知道,选择至少包含标签的所有文章很简单" 14 OR 16 OR 17" ......(只是简单的分离)...

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

当我必须列出带有这些标签的文章"(14 OR 16)AND(17 OR 18)AND NOT(13)&#34时,如何做同样的事情(快速方式,只有一个SQL查询) ; ? ......(否定,结合,分离)...... 感谢您的帮助和想法!


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 ║
╚════════════════╩════════════════════╝

1 个答案:

答案 0 :(得分:1)

我会使用这样的查询:

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