开发者

How to select multiple values from single column with multiple tables in MySQL?

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开发者_StackOverflow = ('green' AND 'orange' AND 'black' AND '...')


Not sure if that fits your need but you might wanna try this:

SELECT DISTINCT table1.name, table3.title
FROM table2
LEFT JOIN (table1, table3)
ON (table2.table1_id = table1.id AND table2.table3_id = table3.id)
WHERE table3.title = 'orange' OR table3.title = 'blue';

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:

SELECT table1.name
FROM table1 
JOIN table2 t1_link ON table1.id = t1_link.table1_id
JOIN table3 t1_data ON t1_link.table3_id = t1_data.id AND t1_data.title in ('blue', 'orange')
JOIN table2 t2_link ON table1.id = t2_link.table1_id
JOIN table3 t2_data ON t2_link.table3_id = t2_data.id AND t2_data.title in ('green', 'black')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜