sql查询更新update select

导读 针对一个上线的项目进行数据库优化,以便后期统计,遇到一个数据填充的问题,在此记录一下,各位如果也有这种问题,欢迎一起交流。

表结构:

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)

终于成功了。Linux就该这么学

猜你喜欢

转载自blog.csdn.net/Linuxprobe18/article/details/111661555