如何使用MySQL中的另一个表值来过滤DELETE语句?

时间:2014-12-10 12:35:36

标签: mysql

我还没有找到一个这样的例子。也许这是不可能的,或者我只是没有使用正确的搜索词。

这很简单:我有一个连接表,其中包含事件的外键:

CREATE TABLE dbp_Join(
Event INT,
Participant INT,
Location INT,
TST TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY(Event) REFERENCES dbp_Events(ID)
    ON UPDATE CASCADE
    ON DELETE CASCADE,
FOREIGN KEY(Participant) REFERENCES dbp_Participants(ID)
    ON UPDATE CASCADE
    ON DELETE CASCADE,
FOREIGN KEY(Location) REFERENCES dbp_Locations(ID)
    ON UPDATE CASCADE
    ON DELETE CASCADE
)ENGINE = INNODB;

我有事件表:

CREATE TABLE dbp_Events(
ID INT auto_increment,
Name Char(80),
ETime DATETIME NOT NULL,
Details VARCHAR(2000),
E_TST TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY(ID, E_TST)
)ENGINE = INNODB;

我在Join表中有值引用参与它们的事件和用户。我想删除Join表中引用2014-12-12事件的所有行。我该如何编写该查询?我可以吗?我想要这样的东西:

DELETE FROM dpb_Join WHERE DATE(dbp_Events.`ETime`)='2014-12-12';

我试过了

DELETE FROM dbp_Join, dbp_Events WHERE DATE(`ETime`)='2014-12-12';

但它不起作用,它只是清空整个表格。

更新: 尝试了MySQL DELETE引用的一个例子,它似乎是正确的方法,但它没有删除任何东西:

DELETE dbp_join FROM dbp_join INNER JOIN dbp_events
WHERE DATE(dbp_events.ETime='2014-12-12');

2 个答案:

答案 0 :(得分:1)

我在这里看不到问题!?!?

 DROP TABLE IF EXISTS events;

 CREATE TABLE events (event_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,event_date DATE NOT NULL);

 INSERT INTO events (event_date) VALUES ('2014-12-12'),('2014-12-13');

 CREATE TABLE event_participants (event_id INT NOT NULL,participant VARCHAR(12) NOT NULL,PRIMARY KEY(event_id,participant));

 INSERT INTO event_participants VALUES (1,'Adam'),(1,'Bob'),(2,'Adam'),(2,'Charles');

 SELECT * FROM events;
 +----------+------------+
 | event_id | event_date |
 +----------+------------+
 |        1 | 2014-12-12 |
 |        2 | 2014-12-13 |
 +----------+------------+

 SELECT * FROM event_participants;
 +----------+-------------+
 | event_id | participant |
 +----------+-------------+
 |        1 | Adam        |
 |        1 | Bob         |
 |        2 | Adam        |
 |        2 | Charles     |
 +----------+-------------+

 DELETE ep FROM events e JOIN event_participants ep ON ep.event_id = e.event_id WHERE e.event_date = '2014-12-12';
 Query OK, 2 rows affected (0.03 sec)

 SELECT * FROM events;
 +----------+------------+
 | event_id | event_date |
 +----------+------------+
 |        1 | 2014-12-12 |
 |        2 | 2014-12-13 |
 |        3 | 2014-12-12 |
 |        4 | 2014-12-13 |
 +----------+------------+

 SELECT * FROM event_participants;
 +----------+-------------+
 | event_id | participant |
 +----------+-------------+
 |        2 | Adam        |
 |        2 | Charles     |
 +----------+-------------+

答案 1 :(得分:1)

JOIN会使删除变慢。改为使用IN子句。

DELETE FROM dbp_Join WHERE Event IN (
    SELECT ID FROM dbp_Events WHERE ETime = DATE('2014-12-12')
)

另见

Delete with Join in MySQL