我有一个具有指定id,value1,value2和value3
的表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 value1,value2 FROM MyTable1 WHERE value1 = 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 AND MyTable2.value1 = MyTable1.value1 AND MyTable2.value2 = MyTable1.value2
无论如何,我想要这个结果。
+--------+--------+---------+
| VALUE1 | VALUE2 | STATUS |
+--------+--------+---------+
| 103 | 202 | |
| 103 | 203 | WOW |
| 103 | 205 | |
+--------+--------+---------+
感谢!!!
答案 0 :(得分: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以防您需要在value3上进行聚合
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
答案 1 :(得分: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
答案 2 :(得分:-1)
SELECT
mt1.value1,
mt1.value2,
mt2.status
from mytable1 mt1, mytable2 mt2
where mt1.value1 = mt2.value1 and mt1.value1 = 103