mysql删除一张表的一条语句,但是关联到多张表

标签 mysql join sql-delete

我需要删除所有超过一年的公共(public)消息,其中用户(消息所有者、发件人)必须来自澳大利亚且年满 21 岁。

我收到错误:

***#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inner join User inner join City inner join Country where Message.messa' at line 2***.

我的文本甚至没有涵盖任务的一半,所以如果有人可以帮助我。

这是我的代码:

delete 
from Message
     inner join User 
     inner join City 
     inner join Country
where Message.message_type=0 and 
      datediff(curdate(),Message.posted) >366 and 
      User.user_id=Message.owner_id and 
      datediff(User.date_of_birth, 
               str_to_date('1/01/1991', '%m/%d/%Y')) < 366 and            
      City.city_id=User.city_id  and 
      Country.country_id=City.country_id and 
      Country.name='Australia'  

最佳答案

这是因为User是MySQL中的保留关键字,因此您需要用引号将其背光 User :

DELETE Message
FROM Message
     INNER JOIN `User`
        ON `User`.user_id = Message.owner_id
     INNER JOIN City
        ON City.city_id = `User`.city_id
     INNER JOIN Country
        ON Country.country_id = City.country_id
WHERE Message.message_type = 0 AND
      DATEDIFF(CURDATE(), Message.posted) > 366 AND
      ROUND(DATEDIFF(CURDATE(), `User`.date_of_birth)/365) < 21 AND
      Country.name = 'Australia';

或者,如果您将连接条件放在 WHERE 子句中,则无需使用 INNER JOIN :

delete Message
from Message, `User`, City, Country
where `User`.user_id=Message.owner_id and
      City.city_id=`User`.city_id and
      Message.message_type=0 and
      Country.country_id=City.country_id and
      datediff(curdate(),Message.posted) >366 and
      datediff(`User`.date_of_birth,
      str_to_date('1/01/1991', '%m/%d/%Y')) < 366 and
      Country.name='Australia';

关于mysql删除一张表的一条语句,但是关联到多张表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12048934/

相关文章:

php - 更新表格,我做错了什么?

mysql - 使用 WHERE 子句从 MySQL 中同一表的行中删除

PHP 删除查询不起作用,甚至没有收到任何错误消息

mysql - 合并MySQL多表删除语句

php - 如何在两个不同的表中进行搜索?

sql - 如何合并多个 SELECT 结果?

mysql查询将字符串与int值进行比较

mysql - 如何将一个表多次加入另一个表

hadoop - 在 PIG 中完全外部连接后丢弃空值

mysql - 加入具有多个引用和两个要添加的值的两个表