如果您已经从MEMBERS
表中删除了行,并且您想从其他两个表中删除列的值与表中任何行的值OWNER
都不匹配的行:NAME
MEMBERS
DELETE h.*
FROM `HOMES` h
LEFT
JOIN `MEMBERS` m
ON m.`NAME` = h.`OWNER`
WHERE m.`NAME` IS NULL
DELETE c.*
FROM `CARS` c
LEFT
JOIN `MEMBERS` m
ON m.`NAME` = c.`OWNER`
WHERE m.`NAME` IS NULL
(注意,这些语句还将从列中删除行,HOMES
并将CARS
列OWNER
作为 NULL 值。)
我强烈建议您在运行 DELETE 之前使用 SELECT 运行这些语句的测试。(将关键字DELETE替换为关键字SELECT,即
-- DELETE h.*
SELECT h.*
FROM `HOMES` h
LEFT
JOIN `MEMBERS` m
ON m.`NAME` = h.`OWNER`
WHERE m.`NAME` IS NULL
展望未来,如果您想保持这些表“同步”,您可以考虑使用 ON CASCADE DELETE 选项定义 FOREIGN KEY 约束。
或者,您可以使用删除所有三个表中的行的 DELETE 语句:
DELETE m.*, h.*, c.*
FROM `MEMBERS` m
LEFT
JOIN `HOMES` h
ON h.`OWNER` = m.`NAME`
LEFT
JOIN `CARS` c
ON c.`OWNER` = m.`NAME`
WHERE UNIX_TIMESTAMP()-m.`LAST_LOGGED_IN` > 864000
(N.B. the predicate there cannot make use of an index on the LAST_LOGGED_IN
column. An equivalent predicate with a reference to the "bare" column will be able to use an index.
WHERE m.`LAST_LOGGED_IN` < UNIX_TIMESTAMP()-864000
or an equivalent:
WHERE m.`LAST_LOGGED_IN` < UNIX_TIMESTAMP(NOW() - INTERVAL 10 DAY)
For best performance, you would need indexes on both HOMES
and CARS
with a leading column of OWNER
, e.g.
... ON `HOMES` (`OWNER`)
... ON `CARS` (`OWNER`)