mysql query with AND, OR and NOT

若如初见. 提交于 2019-11-30 14:33:30

The ALL and NOT parts are very simple, you just chain them with ANDs:

SELECT X FROM Y WHERE a AND b AND c AND NOT d AND e AND NOT e.

And the ORs go between:

SELECT X FROM Y WHERE ((a AND b AND c) AND (d OR e OR f)) AND NOT g AND NOT h

replace small numbers with comparisons and you're done. So if you want to do this in code, sort your conditions and then just chain them together as a String. Be careful to avoid SQL-Insertions.

If I get this correctly

    SELECT * FROM ArticleTopics where type = 'AND'
UNION
    SELECT * FROM ArticleTopics where type = 'OR' limit 1

I assume by 'any' you mean 'any one'. You can join the articles to topics yourself, that's trivial.

Poonam Bhatt
SELECT a.id, a.name 
  FROM Articles a, ArticleTopics arto
  WHERE arto.article_id = a.id 
    AND 
      ((arto.topic_id = 1 AND arto.type like 'AND') AND (arto.topic_id = 2 AND arto.type like 'AND') AND (arto.topic_id = 3 AND arto.type like 'AND')) 
    AND
      ((arto.topic_id = 4 AND arto.type like 'OR') AND (arto.topic_id = 5 AND arto.type like 'OR') AND (arto.topic_id = 6 AND arto.type like 'OR'))
    AND
      ((arto.topic_id = 7 AND arto.type like 'NOT') AND (arto.topic_id = 8 AND arto.type like 'NOT'))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!