문제

I am working on a SQL Server 2008 database where all items that can be used in the database are stored in table A with a key value of ItemNum. Table B and Table C use ItemNum as a key value and are where the items from table A are actually used. Table A contains many duplicates that aren't used in Table B and Table C. I need to delete all ItemNum from Table A that are not used in tables B or table C.

Right now I have the following two queries using Select statements (which will eventually be switched to Delete statements) which I am not sure are working correctly, and I want to create the most efficient query possible.

    USE Database
    GO

    SELECT ItemNum 
    FROM B
    WHERE EXISTS 
        (SELECT ItemNum FROM A WHERE A.ItemNum = B.ItemNum)

    USE Database
    GO

    SELECT ItemNum 
    FROM C
    WHERE EXISTS
        (SELECT ItemNum FROM A WHERE A.ItemNum = C.ItemNum)
도움이 되었습니까?

해결책

You could use a simple DELETE JOIN;

DELETE A FROM A 
LEFT JOIN B ON A.itemnum = B.itemnum
LEFT JOIN C ON A.itemnum = C.itemnum
WHERE b.itemnum IS NULL
  AND c.itemnum IS NULL;

An SQLfiddle to test with.

다른 팁

Something like this?:

DELETE FROM TableA WHERE ItemNum NOT IN(SELECT ItemNum FROM TableB) and ItemNum NOT IN(SELECT ItemNum FROM TableC)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top