SQL查询以查找表中的缺失值

时间:2019-01-11 11:52:00

标签: sql sql-server

表1

1539  1547 E GED     : Failed to execute ioctl 3222824709, BridgeID(5), err(-1)
1539  1547 E GasService: Error on query GED info, err=1
1539  1547 E GED     : Failed to execute ioctl 3222824709, BridgeID(5), err(-1)
1539  1547 E GasService: Error on query GED info, err=1
1060  1161 E ApplockRunningService.TAG: AppLockService------------->tasks = [android.app.ActivityManager$RunningTaskInfo@40598b4]
1060  1161 E ApplockRunningService.TAG: AppLockService------------->packname = com.android.launcher3
1060  1161 E ApplockRunningService.TAG: getLockFlag------------> c = android.content.ContentResolver$CursorWrapperInner@a210cdd

表2

FOR INSERT OR UPDATE ON MODERADORES

这是背景 表1包含产品数据,表2包含具有订单ID的产品数据 我想知道没有订购多少产品(在这种情况下,“ CBD软件”和“ DEF许可证”没有下订单,因此表2中缺少)。 现在我想知道从未在订单上下过多少产品。

4 个答案:

答案 0 :(得分:2)

您只想要[codepen]https://codepen.io/ranjith555/pen/OyKjjm 吗?

not exists

答案 1 :(得分:2)

您还可以在LEFT JOIN条件下使用IS NULLwhere

SELECT t1.*
FROM table1 t1
LEFT JOIN table2 t2 ON t2.product = t1.product
WHERE t2.product IS NULL

答案 2 :(得分:1)

您可以尝试以下查询

SELECT * FROM Table1
where ProductId not in (SELECT ProductId FROM ProductDescription)

下面是实际示例

Create table ProductDescription (ProdCd varchar(10), ProdDes Varchar(20))
insert into ProductDescription values ('ABC', 'Hardware'),
('CBD',     'Software'),
('BCQ',     'Component'),
('DEF',     'License')

Create table ProductOrders (ProdCd varchar(10), ProdDes Varchar(20), OrderId int)
insert into ProductOrders values ('ABC',      'Hardware',      1234),
('ABC',      'Hardware',      2345),
('ABC',      'Hardware',      5678),
('BCQ',      'Component',     7896),
('BCQ',      'Component',     9681)

SELECT * FROM ProductDescription
where ProdCd not in (SELECT ProdCd FROM ProductOrders)

输出如下所示

ProdCd  ProdDes
---------------
CBD     Software
DEF     License

您可以在Live Demo

中找到实时演示

答案 3 :(得分:1)

这是另一种方式,使用RIGHT JOINIS NULL

declare @prod table
(
    Product varchar(100),
    [product Description] varchar(100)
)

insert into @prod
select 'ABC','Hardware' union
select 'CBD','Software' union
select 'BCQ','Component' union
select 'DEF','License'


declare @prodOrders table
(
    Product varchar(100),
    [product Description] varchar(100),
    [orderid] int
)
insert into @prodOrders
select 'ABC','Hardware',1234  union
select 'ABC','Hardware',2345  union
select 'ABC','Hardware',5678  union
select 'BCQ','Component',7896 union
select 'BCQ','Component',9681

SELECT t1.*
FROM @prodOrders t2 
right JOIN @prod t1 ON t2.product = t1.product
WHERE t2.product IS NULL

Live Demo