MySQL语句中的令牌无效

时间:2015-12-24 03:07:56

标签: mysql sql sql-delete

我正在尝试使用此question中的解决方案删除MySql数据库中的重复项,保留1行。

DELETE
  e1
FROM
  email e1,
  email e2
WHERE
  e1.email = e2.email AND e1.pnum > e2.pnum

但我一直得到一个"无效令牌" DELETE别名出错。

enter image description here

我做错了什么?

MYSQL VERSION

服务器:通过UNIX套接字的Localhost 服务器类型:MySQL 服务器版本:5.7.10 - MySQL社区服务器(GPL) 协议版本:10

2 个答案:

答案 0 :(得分:1)

create table email
(   -- the columns here aren't great, but illustrative
    id int auto_increment primary key,
    email text not null,
    rcvDate datetime not null
);

-- truncate table email;
insert email(email,rcvDate) values
('this is an email','2015-12-01 08:00:01'),
('greetings email','2015-12-01 09:00:01'),
('this is an email','2015-12-01 10:00:01'),
('this is an email','2015-12-01 11:00:01'),
('yet another email','2015-12-01 12:00:01');

select * from email;
+----+-------------------+---------------------+
| id | email             | rcvDate             |
+----+-------------------+---------------------+
|  1 | this is an email  | 2015-12-01 08:00:01 |
|  2 | greetings email   | 2015-12-01 09:00:01 |
|  3 | this is an email  | 2015-12-01 10:00:01 |
|  4 | this is an email  | 2015-12-01 11:00:01 |
|  5 | yet another email | 2015-12-01 12:00:01 |
+----+-------------------+---------------------+

删除查询

delete from  email
where concat(email, id) not in 
(   select dummy 
    from
    (   select concat(email, max(id)) as dummy
        from email
        group by email
    ) xDerived
);

结果

select * from email;
+----+-------------------+---------------------+
| id | email             | rcvDate             |
+----+-------------------+---------------------+
|  2 | greetings email   | 2015-12-01 09:00:01 |
|  4 | this is an email  | 2015-12-01 11:00:01 |
|  5 | yet another email | 2015-12-01 12:00:01 |
+----+-------------------+---------------------+

受到https://stackoverflow.com/a/4606939/1816093

的马丁史密斯的启发

可以使用rcvDate作为最大值。

答案 1 :(得分:0)

DELETE查询的正确语法在DELETE和FROM之间不需要任何内容 http://dev.mysql.com/doc/refman/5.7/en/delete.html

您的查询应采用此格式

DELETE FROM email e1, email e2 WHERE e1.email = e2.email AND e1.pnum > e2.pnum