V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
uti6770werty
V2EX  ›  MySQL

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

  •  
  •   uti6770werty · 2020-08-31 17:37:24 +08:00 · 1962 次点击
    这是一个创建于 1327 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    5 条回复    2020-09-01 09:32:45 +08:00
    kiracyan
        1
    kiracyan  
       2020-08-31 18:49:22 +08:00   ❤️ 1
    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
        2
    LGA1150  
       2020-08-31 20:24:04 +08:00 via Android   ❤️ 1
    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
        3
    uti6770werty  
    OP
       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
        4
    gavindexu  
       2020-09-01 05:57:54 +08:00 via iPhone
    给中文的字段名前后加上“`”就可以了啊
    muskill
        5
    muskill  
       2020-09-01 09:32:45 +08:00
    @LGA1150 直接 delete 不好吧😳
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1091 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 18:39 · PVG 02:39 · LAX 11:39 · JFK 14:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.