【问题标题】:not exists but not returning any results不存在但不返回任何结果
【发布时间】:2022-09-14 04:23:11
【问题描述】:

有1张桌子。

ParentServiceCategoryID ServiceName Entity TypeID mapped
1 landscape 5
1 landscape 6
1 landscape 7
1 Trimmings 88
1 Trimmings 8
1 Trimmings 99

该公司提供 3 项服务:景观、修剪和铲土。
父服务 ID 称为“户外服务”

我正在尝试识别没有“铲”的户外服务。上面的示例将被捕获。如果该服务“铲除”了相同的父服务类别(户外服务),那么我不希望它被捕获。

尝试执行“不存在”但未返回任何结果

尝试的代码:

SELECT * 
FROM table1 t1
WHERE NOT EXISTS
     (select * FROM table1 t2 
       where t1.ParentServiceCategoryID=t2.ParentServiceCategoryID
       AND t2.ServiceName='Shoveling'
     )

【问题讨论】:

  • 您的查询适用于您提供的示例数据:db<>fiddle
  • 也许你需要检查大小写?

标签: sql-server subquery not-exists


【解决方案1】:

使用你查询它返回的数据除了“铲”

declare @Table1 as table  
(
ParentServiceCategoryID int,    ServiceName varchar(8000),
EntityTypeIDmapped int)  
insert into @Table1
values  
(1, 'landscape',    5 ),  
(1, 'landscape',    6 ),  
(1, 'landscape',    7 ),  
(1, 'Trimmings',    88),  
(1, 'Trimmings',    8 ),  
(1, 'Trimmings',    99)  

SELECT * 
FROM @table1 t1
WHERE NOT EXISTS  
     (select * FROM @table1 t2   
       where t1.ParentServiceCategoryID=t2.ParentServiceCategoryID   
       AND t2.ServiceName='Shoveling'
     ) 
       

您可以使用以下查询来实现上述数据

SELECT * 
FROM @Table1 t1
where ServiceName not in('Shoveling')

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 2017-12-09
    • 2020-10-03
    • 2017-03-19
    • 2017-05-20
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多