7

我有这种删除查询:

DELETE 
FROM SLAVE_TABLE
WHERE ITEM_ID NOT IN (SELECT ITEM_ID FROM MASTER_TABLE)

有没有办法优化这个?

4

2 回答 2

3

(NOT) IN通常可以通过使用(NOT) EXISTS来优化。

DELETE 
FROM SLAVE_TABLE
WHERE NOT EXISTS (SELECT 1 FROM MASTER_TABLE M WHERE M.ITEM_ID = ITEM_ID)

我不确定你在这里要做什么,但对我来说,这个查询表明你应该使用外键来强制执行这些约束,而不是运行查询来清理之后的混乱。

于 2012-09-16T08:00:16.703 回答
3

您可以使用 EXECUTE BLOCK 顺序扫描明细表并删除没有匹配主记录的记录。

EXECUTE BLOCK
AS
  DECLARE VARIABLE C CURSOR FOR
    (SELECT d.id
     FROM detail d LEFT JOIN master m
       ON d.master_id = m.id
     WHERE m.id IS NULL);
  DECLARE VARIABLE I INTEGER;
BEGIN
  OPEN C;
  WHILE (1 = 1) DO
  BEGIN
    FETCH C INTO :I;
    IF(ROW_COUNT = 0)THEN
      LEAVE;
    DELETE FROM detail WHERE id = :I;
  END
  CLOSE C;
END
于 2012-09-17T08:22:35.223 回答