2015-07-04 53 views
2

表1)m_conservationsetting表1左連接表2負(連接數據)

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單位類別編號)

表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 

表1需要保留與表2連接,它應該省略連接結果並僅顯示錶1數據作爲結果。 Table1 LeftJoin Table2 - (join Data)for the following query。用於獲取結果的條件是檢查狀態= 0備案表2中

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

爲什麼你使用'LEFT JOIN'如果只想那些在表2中的特定狀態行? – Barmar

+0

如果使用'GROUP BY cs.CategoryId',則不能在結果中得到具有相同'CategoryId'的兩行。 – Barmar

+0

你想得到的結果不僅僅是左連接檢查結果的值,你還有一個值是左連接結果1,1,2 –

回答

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 
) 
+0

感謝您的時間,但奎雷沒有給出預期的結果。 – neo

+0

@neo你能告訴我這個查詢爲你提供的相同數據帶來了什麼結果,因爲我還沒有測試過,如果你可以請'小提琴'。 –

2

只有左連接足以獲得結果。

Set Nocount On; 

Declare @table1 Table 
(
    FacilityId   Int 
    ,Unit    Int 
    ,CategoryId   Int 
) 

Declare @table2 Table 
(
    FacilityId   Int 
    ,Unit    Int 
    ,CategoryId   Int 
    ,[Status]   Bit 
) 

Insert Into @table1(FacilityId,Unit,CategoryId) Values 
(1,1,1) 
,(1,1,2) 
,(1,1,3) 
,(1,2,1) 
,(1,2,2) 
,(2,1,1) 
,(2,2,1) 

Insert Into @table2(FacilityId,Unit,CategoryId,[Status]) Values 
(1,1,1,0) 
,(1,1,2,1) 
,(1,1,3,0) 
,(1,2,1,0) 
,(2,1,1,0) 
,(2,2,1,0) 

Select t1.* 
From @table1 As t1 
     Left Join @table2 As t2 On t1.FacilityId = t2.FacilityId 
      And t1.Unit = t2.Unit 
      And t1.CategoryId = t2.CategoryId 
Where t2.FacilityId Is Null 

輸出: -

enter image description here

+0

感謝您的回答,但我必須考慮表2(t2)中的狀態條件是否t2.Status = 0。然後我無法得到上述結果。 – neo

+0

爲了檢查** table2.status = 0 **,不應該在** table2 **中有記錄'(1,2,2,0)'?但是,那麼與那些使用** table2.status = 0 **(以及** table1 **中的相應相關記錄)的所有其他記錄相比,該記錄會是什麼特別的? – Abecee