Trying to delete when not exists is not working. Multiple columns in primary key

巧了我就是萌 提交于 2019-12-10 15:09:32

问题


I am currently trying to delete from Table A where a corresponding record is not being used in Table B. Table A has Section, SubSection, Code, Text as fields, where the first three are the Primary Key. Table B has ID, Section, SubSection, Code as fields, where all four are the Primary Key. There are more columns, but they are irrelevant to this question...just wanted to point that out before I get questioned on why all columns are part of the Primary Key for Table B. Pretty much Table A is a repository of all possible data that can be assigned to a entity, Table B is where they are assigned. I want to delete all records from table A that are not in use in Table B. I have tried the following with no success:

DELETE FROM Table A 
WHERE NOT EXISTS (SELECT * from Table B 
WHERE A.section = B.section
AND A.subsection = B.subsection
AND A.code = b.code)

If I do a Select instead of a delete, I get the subset I am looking for, but when I do a delete, I get an error saying that there is a syntax error at Table A. I would use a NOT IN statement, but with multiple columns being part of the Primary Key, I just don't see how that would work. Any help would be greatly appreciated.


回答1:


In sql server,when using not exists, you need to set an alias for the table to be connected, and in the delete statement, to specify the table to delete rows from.

DELETE a FROM Table_A a 
WHERE NOT EXISTS (SELECT * from Table_B b 
WHERE a.section = b.section
AND a.subsection = b.subsection
AND a.code = b.code)



回答2:


Please try :

DELETE FROM Table A 
WHERE NOT EXISTS (SELECT 1 from Table B 
WHERE A.section = B.section
AND A.subsection = B.subsection
AND A.code = b.code)

1 is just a placeholder, any constant/single non-null column will work.




回答3:


Try something like this:

delete from Table_A
    where (section, subsection, code) not in (select section, 
                                                     subsection, 
                                                     code 
                                                from Table_B)


来源:https://stackoverflow.com/questions/19803023/trying-to-delete-when-not-exists-is-not-working-multiple-columns-in-primary-key

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