我有两个表,table1
和table2
。 Table2
包含来自table1
的FK。目前,我的table2
已经拥有table1
中不存在的FK。我想从table2
中删除那些table1
中不存在FK的记录。这是什么SQL?
这是我尝试过的“NOT IN”:
SELECT ATTORNEYS.ATTY_ID, ATTNY_PRACTICE_GROUPS.ATTY_ID, ATTNY_PRACTICE_GROUPS.ID, ATTNY_PRACTICE_GROUPS.PRACTICE_GRP_ID
FROM ATTORNEYS INNER JOIN ATTNY_PRACTICE_GROUPS ON ATTORNEYS.[ATTY_ID] = ATTNY_PRACTICE_GROUPS.[ATTY_ID]
WHERE ATTNY_PRACTICE_GROUPS.[ATTY_ID] NOT IN ATTORNEYS.ATTY_ID
我可能不知道如何使用“NOT IN”,因为错误是IN运算符而没有表达式中的。(
我已尝试使用!=
,<>
,NOT IN
和IS NULL
,但到目前为止还没有运气。感谢任何帮助。
答案 0 :(得分:2)
SELECT ID
FROM ATTNY_PRACTICE_GROUPS G
WHERE NOT EXISTS (SELECT 1 FROM ATTORNEYS WHERE ATTY_ID = G.ATTY_ID)
此查询将查找任何ATTY_ID不在ATTORNEYS中的Attny_practice_group行。
答案 1 :(得分:0)
你需要的是LEFT JOIN。您的INNER JOIN仅为您提供要保留的记录。您的NOT IN声明不会在此处返回任何结果。将INNER JOIN更改为LEFT JOIN并选择ATTNY_PRACTICE_GROUPS。[SomeColumn] IS NULL
所以这样:
SELECT ATTORNEYS.ATTY_ID, ATTNY_PRACTICE_GROUPS.ATTY_ID, ATTNY_PRACTICE_GROUPS.ID, ATTNY_PRACTICE_GROUPS.PRACTICE_GRP_ID
FROM ATTORNEYS LEFT JOIN ATTNY_PRACTICE_GROUPS ON ATTORNEYS.[ATTY_ID] = ATTNY_PRACTICE_GROUPS.[ATTY_ID]
WHERE ATTNY_PRACTICE_GROUPS.[ATTY_ID] IS NULL
或许我读错了。如果您正在寻找具有ATTORNEYS表中不存在的ATTY_ID的练习组,它将是这样的:
SELECT ATTNY_PRACTICE_GROUPS.ID, ATTNY_PRACTICE_GROUPS.PRACTICE_GRP_ID, ATTORNEYS.ATTY_ID
FROM ATTNY_PRACTICE_GROUPS LEFT JOIN ATTORNEYS ON ATTORNEYS.[ATTY_ID] = ATTNY_PRACTICE_GROUPS.[ATTY_ID]
WHERE ATTORNEYS.[ATTY_ID] IS NULL