Reputation: 946
I feel like I am a decent SQL programmer; however, I came upon a situation that I can't seem to find an elegant solution to solve. There are two tables in my database, a tmp_media table and a tbInventoryMedia table. I want to delete all of the media from tbInventoryMedia that does not exist in the tmp_media table. However, there is a distinct column called VIN - some VINs can have the same media as others.
Example:
tmp_media
Vin MediaId
X 20223
Y 54235
Z 20223
tbInventoryMedia
vin MediaId
X 20223
X 32131
Y 54235
Z 20223
In the above example, the vin of X would be deleted where mediaId is 34131.
Lastly, tmp_media does not contain an exhaustive list of all VINs, only those that have been recently processed. So there will be other media in tbInventoryMedia that needs to be left alone. Only VINs that are located in the tmp_media table are to have any data removed.
If additional clarification is needed, let me know - I imagine that this is very confusing.
Upvotes: 2
Views: 125
Reputation: 41549
This should illustrate my take on your requirements:
create table #tmp_media (VIN char(1), MediaID int)
create table #tbInventoryMedia (VIN char(1), MediaID int)
insert #tmp_media
select Vin = 'X', MediaId=20223
union select 'Y', 54235
union select 'Z', 20223
insert #tbInventoryMedia
select vin = 'X', MediaId = 20223
union select 'X', 32131
union select 'Y', 54235
union select 'Z', 20223
union select 'A', 20223
union select 'A', 12345
select * from #tbInventoryMedia
delete im
from
#tbInventoryMedia im
join (select distinct VIN from #tmp_media) as uq on uq.VIN = im.VIN
left join #tmp_media m on m.MediaID = im.MediaID and m.VIN = im.VIN
where m.MediaID is null
select * from #tbInventoryMedia
drop table #tmp_media
drop table #tbInventoryMedia
I've added some data for the "A" VIN, which I beleive should be left alone. In this example only X, 32131
gets removed
Upvotes: 4