Mysql从一个表中删除一个语句,但与多个表有关

时间:2012-08-21 05:32:07

标签: mysql join sql-delete

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

我收到错误:

  

***#1064 - 您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以便在'内部联接附近使用正确的语法用户内部联接城市内部联接国家,其中Message.messa'在第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'  

2 个答案:

答案 0 :(得分:1)

试试这个:

当你使用两个表进行内连接时,你必须给出一个条件来加入两个表中的条件..

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

答案 1 :(得分:1)

这是因为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';