sql - 确定仅存在于两个表之一或两个表中的值

标签 sql sql-server-2008

我想在 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 

最佳答案

要查找一个表中存在的值而不是另一个表中存在的值,您应该使用 where 子句来确定空值:

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)


--Values Present in both Table

SELECT t.* 
FROM #temp t
    INNER JOIN #_temp1 t1
        ON t.[ATM Int] = t1.[ATM Int]
        AND t.[Fault Int] = t1.[Fault Int]

--Values Present in First Table But not in Second

SELECT t.* 
FROM #temp t
    LEFT JOIN #_temp1 t1
        ON t.[ATM Int] = t1.[ATM Int]
        AND t.[Fault Int] = t1.[Fault Int]
WHERE t1.[ATM Int] IS NULL

--Values Present in Second Table But not in First

SELECT t.* 
FROM #_temp1 t
    LEFT JOIN #temp t1
        ON t.[ATM Int] = t1.[ATM Int]
        AND t.[Fault Int] = t1.[Fault Int]
WHERE t1.[ATM Int] IS NULL

关于sql - 确定仅存在于两个表之一或两个表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13219260/

相关文章:

mysql - 如何让 Round() 的第二个参数与列一起使用?

mysql - 从两个表创建摘要?

sql - 在sql server中舍入小数

php - SQL查询优化

SQL 获取日期中 15 日第一次出现的情况

c# - 如何通过 Dapper 传播 SQL 消息选项卡输出

sql - 如果 SQL 中日期列重叠,则合并行

c# - 在数据库列中存储尺寸(连同图像)?

sql-server-2008 - BCP 双引号文本限定符输出

sql - 在 SQL Server 2008 中使用嵌套 CASE 语句