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
tomoya92
V2EX  ›  MySQL

求 SQL 语句,感兴趣的进来看看吧

  •  
  •   tomoya92 · 2015-05-29 13:09:34 +08:00 · 2348 次点击
    这是一个创建于 3257 天前的主题,其中的信息可能已经有所发展或是发生改变。

    今天碰到一个更新MySQL数据库数据的问题,请教一下大家:
    表:

    要求:根据字段2分组,然后修改对应id最大的那条将字段3修改成1,结果如下:

    使用下面的sql执行,在oracle上是好的,但在mysql上报错

    错误信息:

    这个SQL该怎么写呢?

    7 条回复    2015-05-29 13:44:00 +08:00
    heaton_nobu
        1
    heaton_nobu  
       2015-05-29 13:21:36 +08:00
    不太熟悉mysql,但是sqlserver的语法应该是:
    1. update [table] set ...... where ....
    2. update t set ... from [table] t where ....
    lianyue
        2
    lianyue  
       2015-05-29 13:25:18 +08:00
    update 不能别名 update test set test.xxxx = xxx or update test set xxx = xxxx 只能这样其他问题不知道
    Septembers
        3
    Septembers  
       2015-05-29 13:25:41 +08:00
    Septembers
        4
    Septembers  
       2015-05-29 13:31:57 +08:00
    lianyue
        5
    lianyue  
       2015-05-29 13:31:58 +08:00
    好像是不能别名忘记了 你测试去掉别名看下 或者别名 加上 test as t
    tomoya92
        6
    tomoya92  
    OP
       2015-05-29 13:35:48 +08:00
    @heaton_nobu @lianyue @Septembers
    感谢关注,问题解决了,问题里描述的sql执行报错,不过在oracle里执行是好的
    然后在群里问了下,大家一块试出来了,下面这条sql可以解决
    UPDATE 表 set 字段3 = 1 where id in (
    select a.id from (SELECT max(id) as id FROM 表 GROUP BY 字段2) a );
    b821025551b
        7
    b821025551b  
       2015-05-29 13:44:00 +08:00
    文档是这样写的:
    In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:

    DELETE FROM t WHERE ... (SELECT ... FROM t ...);UPDATE t ... WHERE col = (SELECT ... FROM t ...);{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);

    Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the

    FROM

    clause. Example:

    UPDATE t ... WHERE col = (SELECT (SELECT ... FROM t...) AS _t ...);

    Here the prohibition does not apply because a subquery in the

    FROM

    clause is materialized as a temporary table, so the relevant rows in

    t

    have already been selected by the time the update to

    t

    takes place.

    把update的条件里查询出来的东西起个别名,用这个别名做条件更新,貌似只有mysql是这样
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1877 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:26 · PVG 00:26 · LAX 09:26 · JFK 12:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.