这与mysql query with AND, OR and NOT以及mysql has all values有关我解决了问题的AND
部分,但现在我现在还需要解决OR
和{ {1}}。
只是为了确认以下声明,我给出了所有包含每个主题1,2和3的文章
NOT
我要做的是在查询中添加一些内容,排除所有与主题4和5相关的文章:SELECT x.*
FROM Article x INNER JOIN
(SELECT t.article_id, COUNT(t.article_id)
FROM articleTopics t
WHERE t.topic_id IN ('1','2','3')
GROUP BY t.article_id
HAVING COUNT(t.article_id)>=3
ORDER BY COUNT(t.article_id) DESC
LIMIT 0,100) AS ilv
ON x.id=ilv.article_id
我还想添加主题为6或7的文章,只要它们与之前的约束匹配。
E.g。
NOT
我希望这是有道理的!
答案 0 :(得分:0)
我会使用EXISTS
函数,如:
SELECT ...
FROM Article a
WHERE EXISTS (SELECT topic_id FROM articleTopics t WHERE t.article_id = a.article_id AND topic_id = 1)
AND EXISTS (SELECT topic_id FROM articleTopics t WHERE t.article_id = a.article_id AND topic_id = 2)
AND EXISTS (SELECT topic_id FROM articleTopics t WHERE t.article_id = a.article_id AND topic_id = 3)
AND NOT EXISTS (SELECT topic_id FROM articleTopics t WHERE t.article_id = a.article_id AND topic_id = 4)
AND NOT EXISTS (SELECT topic_id FROM articleTopics t WHERE t.article_id = a.article_id AND topic_id = 5)
AND (EXISTS (SELECT topic_id FROM articleTopics t WHERE t.article_id = a.article_id AND topic_id = 6)
OR EXISTS (SELECT topic_id FROM articleTopics t WHERE t.article_id = a.article_id AND topic_id = 7))
答案 1 :(得分:0)
似乎使用常规JOIN
比使用子选择要简单得多。也应该更快。
SELECT * FROM articles JOIN articleTopics USING(article_id)
WHERE topic_id IN(1,2,3) AND topic_id NOT IN (4,5) GROUP BY article_id;
我不明白为什么你需要指定6和7.除非你说它是否有6或7,否则其他规则无关紧要。在这种情况下你可以这样做:
SELECT * FROM articles JOIN articleTopics USING(article_id)
WHERE (topic_id IN(1,2,3) AND topic_id NOT IN (4,5)) OR topic_id IN(6,7) GROUP BY article_id;
答案 2 :(得分:0)
这就是我最终的结果:
SELECT x.*
FROM Article x INNER JOIN
(SELECT t.article_id, COUNT(t.article_id)
FROM articleTopics t
WHERE t.topic_id IN ('1','2','3')
AND NOT EXISTS (
SELECT 1
FROM articleTopics
WHERE article_id = t.article_id
AND entity_id IN ('4','5'))
GROUP BY t.article_id
HAVING COUNT(t.article_id)>=3
ORDER BY COUNT(t.article_id) DESC
LIMIT 0,100) AS ilv
ON x.id=ilv.article_id
LEFT JOIN articleTopics at ON at.article_id = x.id
WHERE ae_topic_id IN ('6','7')
这表示所有文章必须包含所有主题1,2,3和至少1来自6或7但不包括4或5
感谢您的帮助。