Report missing data in database

断了今生、忘了曾经 提交于 2020-01-05 05:41:07

问题


SQL Fiddle


I have a dynamic long (>1000) list of components and their respective asset types in Excel. Example:

Component                   Asset Type
0738.D100.L00.55            9211.D108.D07.01_02.02
0738.D100.L00.71            0738.D100.L00.55_04.04
0738.D100.M02.55            0738.D100.M00.60_03.03
0990.OH05.A00.09            0738.D100.M00.60_03.03

Some of these combinations may not exist in the SQL database. I want a query that outputs these combinations.

Components and their respective asset type can be requested as follows

Select C.Code, AT.Code From astComponents C 
Join astAssetTypes AT ON AT.Id = C.AssetTypeId

I created a method which uses a temp table to compare with, but tested with 1250 combinations, this method runs slow at ~6.5 seconds, of which creating the table is ~2 seconds.

Create Table 
#Temp(Component nvarchar(50) Collate Latin1_General_BIN, AssetType nvarchar(50) Collate Latin1_General_BIN) 
Insert Into #Temp (Component, AssetType) Values ('0738.D100.L00.55','9211.D108.D07.01_02.02');
Insert Into #Temp (Component, AssetType) Values ('0738.D100.L00.71','0738.D100.L00.55_04.04');
Insert Into #Temp (Component, AssetType) Values ('0738.D100.M02.55','0738.D100.M00.60_03.03');
Insert Into #Temp (Component, AssetType) Values ('0990.OH05.A00.09','0738.D100.M00.60_03.03');
--more Inserts left out

Select Distinct 
    Compare.Component,  
    Compare.AssetType 
From astComponents C
    Join astAssetTypes AT ON AT.Id = C.AssetTypeId
    Right Join #Temp Compare ON Compare.AssetType = AT.Code And Compare.Component = C.Code
Where C.Code is null

In the Fiddle, the expected outcome is below if we use the top example as our data to check. These component-asset type combinations do not exist in the fiddle database.

Component                   Asset Type
0738.D100.M02.55            0738.D100.M00.60_03.03
0990.OH05.A00.09            0738.D100.M00.60_03.03

I want a faster method. Help would be greatly appreciated


回答1:


This query should do what you want:

select c.*
from #temp c join
     astAssetTypes t 
     on t.AssetType = c.AssetType
where not exists (select 1
                  from components co
                  where co.component = c.code and
                        co.AssetTypeId = t.id
                 )  

For this query, you want indexes on:

  • astAssetTypes(AssetType, id)
  • components(component, AssetTypeId)


来源:https://stackoverflow.com/questions/56790755/report-missing-data-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!