mysql - 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 等的内容......我收到了一个无效的结果。
我做错了什么?
解决方案
你说的是 (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)
推荐阅读
- google-apps-script - How do I combine two onEdit functions into one
- vue.js - 在 beforeDestroy 生命周期 vue 中无法通过 getElementById 获取元素
- outlook - 如何使用 vbs 回复电子邮件
- javascript - 我可以在 jquery 的布尔开关滑块中翻译是/否吗?
- c# - C# - WebApi - 特殊字符
- javascript - 如何在下拉菜单中显示模块?
- python - 在为 Django 创建虚拟环境时无法解决这个问题
- javascript - 一旦功能组件中的状态发生变化,如何触发钩子?
- swift - 为什么 didSet 不起作用为什么初始化。?
- python - 是否可以返回带有参数但不调用它的函数?