表1左连接表2减号(连接数据)

时间:2015-07-04 05:55:40

标签: 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          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

2 个答案:

答案 0 :(得分:2)

如果您只想拍摄那些不属于left join结果的记录,请执行以下操作:

SELECT t.* FROM m_conservationsetting AS t
WHERE NOT EXISTS (
    SELECT cs.FacilityId,Cs.Unit,cs.CategoryId 
    FROM m_conservationsetting AS 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 :(得分:2)

只有左连接足以获得结果。 设置Nocount On; 声明@ table1表 (      FacilityId Int     ,Unit Int     ,CategoryId Int ) 声明@ table2表 (      FacilityId Int     ,Unit Int     ,CategoryId Int     ,[状态]位 ) 插入@ table1(FacilityId,Unit,CategoryId)值  (1,1,1) ,(1,1,2) ,(1,1,3) ,(1,2,1) ,(1,2,2) ,(2,1,1) ,(2,2,1) 插入@ table2(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) 选择t1。* 来自@ table1作为t1         Left Join @ table2 as t2 On t1.FacilityId = t2.FacilityId             并且t1.Unit = t2.Unit             并且t1.CategoryId = t2.CategoryId 其中t2.FacilityId为空 输出: -