SQL如何查找不在表中的数据

时间:2016-03-02 19:37:08

标签: sql sql-server

我有这个select语句,我想在结果集中显示found和not-found ... 我的查询只给出了DB中存在的任何值(值)。 如何添加not-found。 例如:

5647994  1234 Data exist in table
5651061  8976 Data exist in table
5823683  null Data not exist in table
6115602  null Data not exist in table

SELECT *
FROM Carrier c
 WHERE (SUBSTRING(c.SrcFileName, 14, 7) in (
'5647994',
'5651061',
'5823683',
'6115602',
'6125795',
'6140114',
'6144781',
'6155133')

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT t1.val,  
       IF (t2.id IS NULL, 'NOT FOUND', 'FOUND'),
       t2.*
FROM (
  SELECT '5647994' AS val UNION ALL SELECT '5651061' UNION ALL
  SELECT '5823683' UNION ALL SELECT '6115602' UNION ALL 
  SELECT '6125795' UNION ALL SELECT '6140114' UNION ALL
  SELECT '6144781' UNION ALL SELECT '6155133') AS t1
LEFT JOIN Carrier AS t2 ON t1.val = SUBSTRING(t2.SrcFileName, 14, 7)

我们的想法是创建一个包含所有待搜索值的内联表。如果我们LEFT JOIN原始表到此内联表,则返回所有值。

上述查询假设idCarrier表的字段。选中NULL / NOT NULL值的此字段可分别识别未找到/找到的值。

答案 1 :(得分:1)

根据其他信息更新。

If(OBJECT_ID('tempdb..#TempSrcFileName') Is Not Null)   Drop Table #TempSrcFileName

CREATE TABLE #TempSrcFileName
(
    src_file_name nchar(7)
)

INSERT INTO #TempSrcFileName (src_file_name)
VALUES
    ('5647994')
    , ('5651061')
    , ('5823683')
    , ('6115602')
    , ('6125795')
    , ('6140114')
    , ('6144781')
    , ('6155133')
;

SELECT
    t.src_file_name
    , 'Found' AS [Status]
FROM #TempSrcFileName t
    LEFT JOIN Carrier c ON SUBSTRING(c.SrcFileName, 14, 7) = t.src_file_name
WHERE   (SUBSTRING(c.SrcFileName, 14, 7) IS NOT NULL)
UNION SELECT
    t.src_file_name
    , 'Not Found' AS [Status]
FROM #TempSrcFileName t
    LEFT JOIN Carrier c ON SUBSTRING(c.SrcFileName, 14, 7) = t.src_file_name
WHERE   (SUBSTRING(c.SrcFileName, 14, 7) IS NULL)