首页 > 解决方案 > MYSQL用AND和OR条件查询同一列

问题描述

我有以下表格:

       Topic                 Content_Topic                Content

id_topic   topic         id_content   id_topic     id_content  content
    1      aaaaa             1            2             1        xxxxx
    2      bbbbb             1            4             2        yyyyy
    3      ccccc             1            5             3        zzzzz
    4      ddddd             2            1             4        wwwww
    5      eeeee             2            3             5        kkkkk
    6      fffff             2            5             6        jjjjj
        ...                  3            3                  ...
                             3            4 
                             3            5 
                                  ... 

我正在尝试运行以下查询,但没有得到我期望的结果:

SELECT content FROM Content_Topic ct
LEFT JOIN Content c ON ct.id_content=c.id_topic
LEFT JOIN Topic t ON ct.id_topic=t.id_topic
WHERE   (ct.id_topic=2 OR ct.id_topic=3) AND 
        ct.id_topic IN (4,7,10) AND 
        (ct.id_topic=5 OR ct.id_topic=9)

我期望的是所有具有 id_topic 2,4,5 或 3,4,5 或 2,7,5 或 3,7,5 等的内容......我收到了一个无效的结果。

我做错了什么?

标签: mysqlrelational-division

解决方案


你说的是 (2 or 3) AND (4 or 7 or 10) AND (5 or 9)

这意味着你永远不会得到任何结果。

y = 2 or 3

x = 4, 7 or 10

z = 5 or 9

在这种情况下,不可能做到x AND y这一点。

我会使用表别名来引用您的 Content_Topic 表 3 次,这样您就可以使您的每个标准都起作用,并且我会使用 Joins 而不是子选择,因为它更快:

SELECT content FROM Content c 
INNER JOIN Content_Topic ct1 ON ct1.id_content=c.id_topic AND (ct1.id_topic=2 OR ct1.id_topic=3)
INNER JOIN Content_Topic ct2 ON ct2.id_content=c.id_topic AND (ct2.id_topic IN (4,7,10))
INNER JOIN Content_Topic ct3 ON ct3.id_content=c.id_topic AND (ct3.id_topic=5 OR ct3.id_topic=9)

推荐阅读