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

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

  •  
  •   zael · May 29, 2015 · 3249 views
    This topic created in 4171 days ago, the information mentioned may be changed or developed.

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

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

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

    错误信息:

    这个SQL该怎么写呢?

    7 replies  •  2015-05-29 13:44:00 +08:00
    heaton_nobu
        1
    heaton_nobu  
       May 29, 2015
    不太熟悉mysql,但是sqlserver的语法应该是:
    1. update [table] set ...... where ....
    2. update t set ... from [table] t where ....
    lianyue
        2
    lianyue  
       May 29, 2015
    update 不能别名 update test set test.xxxx = xxx or update test set xxx = xxxx 只能这样其他问题不知道
    lianyue
        5
    lianyue  
       May 29, 2015
    好像是不能别名忘记了 你测试去掉别名看下 或者别名 加上 test as t
    zael
        6
    zael  
    OP
       May 29, 2015
    @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  
       May 29, 2015
    文档是这样写的:
    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是这样
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1302 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 21:31 · PVG 05:31 · LAX 14:31 · JFK 17:31
    ♥ Do have faith in what you're doing.