左/右连接参考另一个表

时间:2013-03-21 03:40:37

标签: mysql

我正在尝试访问三个表格,如下所示:

+------+------+------+
| ITEM |  PCS |  CSS |
+------+------+------+
| 1099 |    2 |   11 |
| 1098 |    2 |    2 | 
| 1097 |    2 |    1 | 
| 1096 | NULL | NULL | 
| 1095 | NULL | NULL | 
| 1094 | NULL | NULL |  
| 1093 | NULL | NULL | 
| 1092 | NULL | NULL | 
+------+------+------+

但是,我得到的只是:

+------+------+------+
| ITEM |  PCS |  CSS |
+------+------+------+
| 1099 |    2 |   11 |
| 1098 |    2 |    2 | 
| 1097 |    2 |    1 | 
+------+------+------+

//我对我的查询有点困惑,所以这里是我要做的事情的细分:

SELECT CODE
FROM SET2
WHERE MO = MONTH(SYSDATE())
AND YR = YEAR(SYSDATE())

//and then:

SELECT ITEM, PCS, CSS
FROM SET3
WHERE S3.CODE=S2.CODE

//then:

SELECT ITEM
FROM SET1
WHERE S1.ITEM=S3.ITEM

我的桌子

SET1

+------+
| ITEM |
+------+
| 1099 |
| 1098 | 
| 1097 | 
| 1096 | 
| 1095 | 
| 1094 | 
| 1093 | 
| 1092 | 
+------+

SET2

+------+-----+------+
|   YR |  MO | CODE |
+------+-----+------+
| 2013 |   1 |    1 | 
| 2013 |   2 |    2 | 
+------+-----+------+

SET3

+------+-----+------+------+
|  PCS | CSS | CODE | ITEM |
+------+-----+------+------+
|    2 |  11 |    1 | 1099 |
|    2 |   2 |    1 | 1098 | 
|    2 |   1 |    1 | 1097 | 
+------+-----+------+------+

1 个答案:

答案 0 :(得分:2)

你必须使用左连接才能工作:

SELECT SET1.ITEM, PCS, CSS
FROM SET1
LEFT JOIN SET3 ON SET3.ITEM = SET1.ITEM
LEFT JOIN SET2 ON SET2.CODE = SET3.CODE 
    AND SET2.MO = MONTH(SYSDATE()) 
    AND SET2.YR = YEAR(SYSDATE())