用户登录
用户注册

分享至

sql查询更新update select

  • 作者: 黑子39342533
  • 来源: 51数据库
  • 2022-09-20
导读 针对一个上线的项目进行数据库优化,以便后期统计,遇到一个数据填充的问题,在此记录一下,各位如果也有这种问题,欢迎一起交流。

表结构:

当我从其它数据源使用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 <>

使用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 <>

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 <>

终于成功了。

软件
前端设计
程序设计
Java相关