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

2015-05-29 13:09:34 +08:00
 tomoya92

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

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

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

错误信息:

这个SQL该怎么写呢?

2355 次点击
所在节点    MySQL
7 条回复
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
2015-05-29 13:25:18 +08:00
update 不能别名 update test set test.xxxx = xxx or update test set xxx = xxxx 只能这样其他问题不知道
Septembers
2015-05-29 13:25:41 +08:00
Septembers
2015-05-29 13:31:57 +08:00
lianyue
2015-05-29 13:31:58 +08:00
好像是不能别名忘记了 你测试去掉别名看下 或者别名 加上 test as t
tomoya92
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
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是这样

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

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

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

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

© 2021 V2EX