求一句 MySQL SQL 语句,表内指定字段重复的条目,以 UpdateTime 字段排序,只保留最新一条。。。

2020-08-31 17:37:24 +08:00
 uti6770werty

表名:rejectgoods 判断字段:name,size,city,address UpdateTime 是 datetime 类型
表内所有条目,根据判断字段都相同的条目,如果存在>1 条,只保留 UpdateTime 最新的条目,其它删除。。。

1968 次点击
所在节点    MySQL
5 条回复
kiracyan
2020-08-31 18:49:22 +08:00
select rid from rejectgoods t1
exists (select 1 from rejectgoods where t1. name = t2.name ..... and t1.address = t2. address and t1.updatetime < t2.updatetime )

把查出来的 rid 删了
LGA1150
2020-08-31 20:24:04 +08:00
DELETE a
FROM rejectgoods a, rejectgoods b
WHERE a.name = b.name
AND a.size = b.size
AND ... (其他字段省略)
...
AND a.UpdateTime < b.UpdateTime

这样 UpdateTime 较小的就被删除
uti6770werty
2020-08-31 21:40:05 +08:00
@kiracyan
@LGA1150
感谢两位,字段名称是英文的测试没问题,但是中文的字段名不行,
尽管已经试过格式修改,因为不是很了解 MySQL,临急抱佛脚也不是很懂
WHERE t1.`城市` = t2.`城市`
WHERE a.城市 = b.城市的句式,


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 'WHERE a.城市 = b.城市
gavindexu
2020-09-01 05:57:54 +08:00
给中文的字段名前后加上“`”就可以了啊
muskill
2020-09-01 09:32:45 +08:00
@LGA1150 直接 delete 不好吧😳

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/702893

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX