2011-05-21 163 views
0

我有以下3個表如何從MySQL的單個列中選擇多個表中的多個值?

table1的

id name 
---------- 
1  john 
2  dave 
3  eve 

表2

table1_id table3_id 
---------------------- 
    1   2    
    1   3 
    1   5 
    2   2 
    2   3 
    2   4 
    3   1 
    3   5 

表3

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') 

任何建議將非常感激!

UPDATE 一個問題:)

如何選擇每個table1.name其中table3.title =( '綠', '橙' 和 '黑' 和 '...')

回答

1

如果我得到你的問題吧,你接近:

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

太棒了!這解決了我的問題100%。感謝名單! – fl0w 2011-05-21 09:12:09

+0

還有一個問題..當我想要選擇每個table1.name時,查詢將如何顯示table3.title =('green'AND'blue'AND'black'AND'...')Thanx提前! – fl0w 2011-05-21 09:30:22

+1

根據需要替換in子句。如果兩個條件相互關聯,您也可以將它們放在where子句中。 – 2011-05-21 11:11:11

2

不知道是否適合你的需要,但你可能會想試試這個:

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'; 

你可能想擺脫它,現在只是確保每個名稱顯示只有一次DISTINCT的。

銅 羅馬

+0

thanx您的建議!它幾乎解決了我的查詢,但我仍然想知道如何選擇每個table1.name,其中table3.title =('blue'或'orange')** AND('green'或'black')** Thanx提前! – fl0w 2011-05-21 09:00:30