总结:我们需要从基础条件涉及表本身,以及作为一个单独的表的表项中删除
我已经能够重建我们试图使用两个示例表,称为表-A和表-B来解决这个问题。它们的定义如下:
CREATE TABLE table_A
(
id INT UNSIGNED AUTO_INCREMENT,
name VARCHAR(64) NOT NULL,
date DATE NOT NULL,
otherFields_A VARCHAR(64) NOT NULL,
-- many other fields in the table (different from table_B)
-- but not relevant to the question being asked
PRIMARY KEY(id)
);
CREATE TABLE table_B
(
id INT UNSIGNED AUTO_INCREMENT,
name VARCHAR(64) NOT NULL,
date DATE NOT NULL,
otherFields_B VARCHAR(64) NOT NULL,
-- many other fields in the table (different from table_A)
-- but not relevant to the question being asked
PRIMARY KEY(id)
);
中的表中,如下所示:
INSERT INTO table_A(name, date) VALUES('John Doe', '2018-01-01'), ('John Doe', '2018-07-01'), ('John Doe', '2018-12-01'), ('Mary Smith', '2018-08-02'), ('Andy Roberts', '2018-07-02'), ('John Doe', '2018-12-02');
INSERT INTO table_B(name, date) VALUES('Keith Miller', '2018-01-03'), ('Mary Smith', '2018-07-02'), ('John Doe', '2018-07-30');
我们要遍历表-A和删除其中所有条目
table_B.name= table_A.name
AND
table_B.date >= table_A.date
这应该就这么简单:
DELETE table_A
FROM table_A
INNER JOIN table_B
ON table_B.id = table_A.id
AND table_B.date >= table_A.date