ITPub博客

首页 > 数据库 > 数据库开发技术 > sql查询更新update select

sql查询更新update select

数据库开发技术 作者:安全剑客 时间:2020-12-27 22:44:51 0 删除 编辑
针对一个上线的项目进行数据库优化,以便后期统计,遇到一个数据填充的问题,在此记录一下,各位如果也有这种问题,欢迎一起交流。

表结构:

sql查询更新update selectsql查询更新update select

当我从其它数据源使用sql来填充这个表数据时,from_id都是null,因此要使用update来对from_id进行补充。

update t_ch_test t set t.from_id =
(select max(a.id) from t_ch_test a where a.node_id = t.node_id and a.id < t.id)

使用update select来自连接进行更新操作。这个sql在oracle中执行是没有任何问题的,然后,坑爹的是,这个sql在postgresql中编译都报错。而我们项目组用的最多的就是postgresql,因此无语了。

后来百度一下,发现postgresql在update时不支持表别名alis,所以最开始想的是把别名去掉,如下:

update t_ch_test set from_id =
(select max(a.id) from t_ch_test a where a.node_id = node_id and a.id < id)

sql执行是没有问题了,但一查结果,发现from_id全部为null,怎么回事儿呢。

后来在同事的指导下,a.id < id换成了a.id < 100,执行成功,from_id也有值了,但这个100不能是一个固定值呀。后来自己各种试,终于试出来了,不用表别名,直接用表名代替,如下:

update t_ch_test set from_id =
(select max(a.id) from t_ch_test a where a.node_id = t_ch_test.node_id and a.id < t_ch_test.id)

终于成功了。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31559985/viewspace-2745753/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-11-01

  • 博文量
    1407
  • 访问量
    1394865