如何在MySQL中从多个表的单列中选择多个值?
我有以下 3 个表
table1
id name
----------
1 john
2 dave
3 eve
table2
table1_id table3_id
----------------------
1 2
1 3
1 5
2 2
2 3
2 4
3 1
3 5
table3
id title
------------
1 blue
2 orange
3 green
4 yellow
5 black
我试图选择每个 table1.name 其中 table3.title = (蓝色或橙色) AND (绿色或黑色)
以便输出是
name
----
john
dave
这是我迄今为止的查询,不会完成这项工作:
SELECT table1.name
FROM table1
JOIN table2 ON table1.id = table2.table1_id
JOIN table3 t1 ON table2.table3_id = t1.id
JOIN table3 t2 ON t1.title = t2.title
WHERE t1.title IN ('blue', 'orange')
AND t2.title IN ('green', 'black')
任何建议将不胜感激!
更新 还有一个问题:)
如何选择每个 table1.name where table3.title = ('green' AND 'orange' AND 'black' AND '...')
I have the following 3 tables
table1
id name
----------
1 john
2 dave
3 eve
table2
table1_id table3_id
----------------------
1 2
1 3
1 5
2 2
2 3
2 4
3 1
3 5
table3
id title
------------
1 blue
2 orange
3 green
4 yellow
5 black
I'm trying to select each table1.name where table3.title = (blue OR orange) AND (green OR black)
so that the output is
name
----
john
dave
This is my query so far that won't get this job done:
SELECT table1.name
FROM table1
JOIN table2 ON table1.id = table2.table1_id
JOIN table3 t1 ON table2.table3_id = t1.id
JOIN table3 t2 ON t1.title = t2.title
WHERE t1.title IN ('blue', 'orange')
AND t2.title IN ('green', 'black')
Any suggestions would be really appreciated!
UPDATE
One more question :)
How to select each table1.name where table3.title = ('green' AND 'orange' AND 'black' AND '...')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定这是否适合您的需要,但您可能想尝试一下:
您可能想摆脱 DISTINCT,它现在只是确保每个名称仅显示一次。
铜
罗马
Not sure if that fits your need but you might wanna try this:
You might wanna get rid of the DISTINCT which right now just ensures that each name is shown only once.
cu
Roman
如果我正确回答了你的问题,你就很接近了:
If I'm getting your question right, you're close: