2016-01-26 93 views
0

我有一個指定的ID,值1,值和值3MySQL的選擇不同的值,然後選擇更多

MYTABLE1表看起來是這樣的:

+------+--------+--------+--------+ 
| ID | VALUE1 | VALUE2 | VALUE3 | 
+------+--------+--------+--------+ 
| 1 | 103 | 202 | 3212 | 
| 2 | 103 | 202 | 7667 | 
| 3 | 103 | 202 | 7567 | 
| 4 | 103 | 203 | 6545 | 
| 5 | 103 | 203 | 9787 | 
| 6 | 106 | 203 | 6545 | 
| 7 | 106 | 203 | 6575 | 
| 8 | 106 | 202 | 8909 | 
| 9 | 106 | 206 | 4656 | 
| 10 | 106 | 205 | 5676 | 
| 11 | 106 | 208 | 9088 | 
| 12 | 107 | 202 | 8998 | 
| 13 | 107 | 205 | 5675 | 
| 14 | 107 | 204 | 9787 | 
| 15 | 107 | 204 | 6454 | 
| 16 | 107 | 206 | 9089 | 
| 17 | 107 | 202 | 1233 | 
| 18 | 107 | 205 | 8765 | 
| 19 | 108 | 208 | 8900 | 
| 20 | 103 | 205 | 6543 | 
+------+--------+--------+--------+ 

而且MyTable2看起來是這樣的:

+------+--------+--------+---------+ 
| ID | VALUE1 | VALUE2 | STATUS | 
+------+--------+--------+---------+ 
| 1 | 103 | 209 | OK  | 
| 2 | 105 | 203 | DEAD | 
| 3 | 107 | 205 | GOOD | 
| 4 | 104 | 202 | WRONG | 
| 5 | 103 | 203 | WOW  | 
+------+--------+--------+---------+ 

當我想要結果。我正在使用這段代碼。

SELECT DISTINCT值1,值FROM MYTABLE1 WHERE值1 = 103

結果如下所示。

+--------+---------+ 
| VALUE1 | VALUE2 | 
+--------+---------+ 
| 103 | 202  | 
| 103 | 203  | 
| 103 | 205  | 
+--------+---------+ 

但我想添加一個狀態欄和隨之而來MyTable2

我想是這樣的,但我沒有得到的結果。

SELECT DISTINCT MyTable1.value1,MyTable1.value2,MyTable2.status FROM MYTABLE1,MyTable2 WHERE MyTable1.value1 = 103和MyTable2.value1 = MyTable1.value1 AND MyTable2.value2 = MyTable1.value2

無論如何,我想這個結果。

+--------+--------+---------+ 
| VALUE1 | VALUE2 | STATUS | 
+--------+--------+---------+ 
| 103 | 202 |   | 
| 103 | 203 | WOW  | 
| 103 | 205 |   | 
+--------+--------+---------+ 

謝謝!!!

+1

不要使用隱式/逗號連接語法。始終使用顯式的JOIN語法。那麼你的問題就變得微不足道了。 – Strawberry

回答

-1
SELECT 
    mt1.value1, 
    mt1.value2, 
    mt2.status 
from mytable1 mt1, mytable2 mt2 
where mt1.value1 = mt2.value1 and mt1.value1 = 103 
+1

同樣,不要使用逗號連接語法。 – Strawberry

0

使用左連接(因爲我們想從T1的所有記錄,但只有那些匹配T2是)

SELECT DISTINCT T1.value1,T1.value2,T2.status 
FROM MyTable1 T1 
LEFT JOIN MyTable2 T2 
    on T2.value2 = T1.value2 
AND T2.value1 = T1.value1 
WHERE T1.value1 = 103 

或使用GROUP BY的情況下,你需要在價值3聚集

SELECT T1.value1,T1.value2,T2.status 
FROM MyTable1 T1 
LEFT JOIN MyTable2 T2 
    on T2.value2 = T1.value2 
AND T2.value1 = T1.value1 
WHERE T1.value1 = 103 
GROUP BY T1.value1,T1.value2,T2.status 
0

像這樣的東西應該工作:

SELECT DISTINCT 
    tb1.value1, 
    tb1.value2, 
    tb2.status 
FROM 
    table1 tb1 
LEFT JOIN 
    table2 tb2 on tb1.value1 = tb2.value1 
    and tb1.value2 = tb2.value2 
WHERE 
    tb1.value1 = 103