LeftJoin减号(右表数据+内连接数据)

时间:2015-07-03 15:45:25

标签: mysql sql

表1)
m_conservationsetting

+------------+-------+------------+
| FacilityId | Unit  | CategoryId |
+------------+-------+------------+
|     1      |    1  |      1     |
|     1      |    1  |      2     |
|     1      |    1  |      3     |
|     1      |    2  |      1     |
|     1      |    2  |      2     |
|     2      |    1  |      1     |
|     2      |    2  |      1     |
+------------+-------+------------+

唯一键(FacilityId Unit CategoryId)

表2)
l_maintelog

+------------+------+------------+--------+
| FacilityId | Unit | CategoryId | Status |
+------------+------+------------+--------+
|    1       |   1  |      1     |    0   |
|    1       |   1  |      2     |    1   |
|    1       |   1  |      3     |    0   |
|    1       |   2  |      1     |    0   |
|    2       |   1  |      1     |    0   |
|    2       |   2  |      1     |    0   |
+------------+------+------------+--------+

结果:

+------------+------+------------+
| FacilityId | Unit | CategoryId |
+------------+------+------------+
|     1      |  1   |     2      |
|     1      |  2   |     2      |
+------------+------+------------+

Table1需要保留与Table2的连接,它应该省略连接结果并仅显示table1数据作为结果。
表1 LeftJoin表2 - (连接数据)用于以下查询。获得结果的条件是检查表2中记录的状态= 0

查询

select cs.FacilityId,Cs.Unit,cs.CategoryId 
from m_conservationsetting cs 
LEFT JOIN l_maintelog ml on
(cs.FacilityId=ml.FacilityId and cs.Unit=ml.Unit)
WHERE (ml.Status=0
) 
group by cs.CategoryId

1 个答案:

答案 0 :(得分:0)

您可以在Second Table的Key列上使用NULL条件来消除两个表中的结果

Select cs.FacilityId,Cs.Unit,cs.CategoryId 
from m_conservationsetting cs 
LEFT JOIN l_maintelog ml on
(cs.FacilityId=ml.FacilityId and cs.Unit=ml.Unit)
WHERE (ml.Status=0
and ml.FacilityId IS NULL) 
group by cs.CategoryId