2012-11-04 24 views
2

的我有一個SQL Server 2008數據庫的兩個表中,我想找到:目前這兩個表中確定存在於兩個只有一個表中的值,或在兩者

  • 值(用本兩個表中的所有列)本
  • 值在第一表而不是在第二個表
  • 值存在於第二表而不是在第一表

代碼:

CREATE TABLE #_temp 
(ATM INT, Fault INT) 

CREATE TABLE #_temp1 
(ATM INT, Fault INT) 

INSERT INTO #_temp VALUES (10,101), (11,101), (12,101), (12,101), (10,105), (13,101) 
INSERT INTO #_temp1 VALUES (10,102), (11,101), (12,103), (12,100), (10,105), (13,101) 

/* My Try 

SELECT * FROM #_temp t RIGHT JOIN #_temp1 t1 ON t.ATM=t1.ATM AND t.Fault=t.Fault AND t.ATM IS NULL AND t.Fault IS NULL 

SELECT * FROM #_temp t JOIN #_temp1 t1 ON t.ATM=t1.ATM AND t.Fault=t.Fault 

*/ 

DROP Table #_temp 
DROP Table #_temp1 
+0

您需要使用LEFT JOIN,充分聯接,右連接 – user1534664

回答

1

要查找存在於一個表中的值,而不是其他,你應該使用where子句來確定零點:

創建表#_temp (ATM Int,Fault Int)

創建表#_temp1 (ATM In T,故障智力)

插入進#_temp值(10101),(11,101),(12101),(12101),(10105),(13101) 插入插入#_temp1值(10,102,104)(11,101) ,(12103),(12100),(10105),(13101)在這兩個表

SELECT噸

--Values存在。* FROM #TEMP噸 INNER JOIN#_temp1 T1 ON噸。 [ATM Int] = t1。[ATM Int] AND t。[Fault Int] = t1。[Fault Int]

- 值出現在第一個表B中UT不是在第二

SELECT噸。* FROM #TEMP噸 LEFT JOIN#_temp1 T1 ON噸。[ATM INT] = t1時。[ATM INT] 和T。[故障INT] = t1時。[故障INT] 其中T1。[ATM INT] IS NULL

--Values在第二個表存在,但不是在第一

SELECT噸。* FROM #_temp1牛逼 LEFT JOIN #TEMP T1 對T [ATM Int] = t1 [ATM Int] AND t。[Fault Int] = t1。[Fault Int] 其中,T1。[ATM INT] IS NULL

0

重命名列,表應該工作:

SELECT A.ATM AS ATM1, A.FAULT AS FAULT1, B.ATM AS ATM2, B.FAULT AS FAULT2 
FROM #_temp as A, #_temp1 as B 
ON A.ATM = BUT.ATM 

SELECT * FROM #_temp 

SELECT * FROM #_temp1 
+0

在條件缺失這裏 – Shaggy

+0

當兩個表連接到匹配的列名時,我認爲ON是隱含的。 – rharrison33

1
Insert Into #_temp Values(10,101),(11,101),(12,101),(12,101),(10,105),(13,101) 
Insert Into #_temp1 Values(10,102),(11,101),(12,103),(12,100),(10,105),(13,101) 



Select t.* From #_temp t LEFT join #_temp1 t1 on t.ATM=t1.ATM and t.Fault is null 
UNION 
Select t.* From #_temp1 t left join #_temp t1 on t.ATM=t1.ATM and t.Fault is NULL 



Drop Table #_temp 
Drop Table #_temp1 
0

沒有確切的舒爾你正在尋找,另一個

Create Table #_temp 
(ATM Int,Fault Int) 

Create Table #_temp1 
(ATM Int,Fault Int) 

Insert Into #_temp Values(10,101),(11,101),(12,101),(12,101),(10,105),(13,101) 
Insert Into #_temp1 Values(10,102),(11,101),(12,103),(12,100),(10,105),(13,101) 


Select a.*,t.ATM as tATM,t.Fault as tFault,t1.ATM as t1ATM,t1.Fault as t1Fault from 
(
Select t.* From #_temp t 
UNION 
Select t.* From #_temp1 t 
) a 
LEFT join #_temp t on t.ATM=a.ATM and T.Fault = a.Fault 
LEFT join #_temp1 t1 on t1.ATM=a.ATM and T1.Fault = a.Fault 


Drop Table #_temp 
Drop Table #_temp1 
相關問題