MySQL 删除和内连接问题

Issue with MySQL delete and inner join

我需要创建一个查询来删除具有旧 cfc_tournament.

cfc_registration

我的查询:

delete from cfc_registration
inner join cfc_tournament on cfc_tournament.id = cfc_registration.cfcTournamendId
where cfc_registration.cfcTournamentId = cfc_tournament.id and cfc_tournament.createdAt >= DATE_SUB(NOW(),INTERVAL 1 YEAR);

问题:

#1064 - 'inner join cfc_tournament on cfc_tournament.id = cfc_registration.cfcTournamendI' à la line 2

问题出在您的 DELETE FROM 一开始。 您应该使用 DELETE t1 FROM table t1 因为您正在指定要删除的内容。这是在 MySQL 中以这种方式实现的,因为您可以同时从两个表中删除记录。

我相信这应该有效:

DELETE t1
FROM cfc_registration t1
  INNER JOIN cfc_tournament t2
    ON t2.id = t1.cfctournamendid
WHERE
  t1.cfctournamentid = t2.id
  AND t2.createdat >= date_sub( now(), interval 1 YEAR );

我个人更喜欢 exists 语句而不是 inner join 方法

delete from cfc_registration
where exists (
  select 1 from cfc_tournament 
  where cfc_tournament.id = cfc_registration.cfcTournamendId
    and cfc_tournament.createdAt >= DATE_SUB(NOW(),INTERVAL 1 YEAR)
);

顺便说一句:对于内部连接方法,您不需要在内部连接和 where 上都使用 cfc_registration.cfcTournamentId = cfc_tournament.id and。一个就够了

delete cfc_registration 
from cfc_registration
inner join cfc_tournament 
  on cfc_tournament.id = cfc_registration.cfcTournamendId
where cfc_tournament.createdAt >= DATE_SUB(NOW(),INTERVAL 1 YEAR);