使用 mysql 就不太强,而且写的复杂SQL多是 select 查询语句,最怕复杂的 update 语句了。
所以在这里总结一下
- 关联需要更新的表或者根据 需要更新表,来执行更新
有一张订单明细表,我需要 更新 明细表里面的 金额和重量, 这个 更新的依据是 根据 订单明细表里面的 某些数据的 来进行 算出来 重量或者金额 来进行更新的。
当然 这个订单明细表 需要根据 订单主表 来进行查询出来。
首先 第一步 我写出来的SQL ,看起来也不算复杂
UPDATE gwqmshop_process_order_item set total_weight=1*count * (
SELECT units.unitWeight from (
SELECT isrc.total_weight/isrc.count as unitWeight from gwqmshop_process_order_item as isrc
where src_order_item_id=isrc.id
) as units
),
total_amount=total_weight*price
where id in (
SELECT item.id from
(
SELECT it.id from gwqmshop_process_order_item as it
where
it.disabled=0
and it.order_id in (
SELECT o.id from gwqmshop_process_order o where o.disabled=0 and o.data_type=3 and o.createtime>'2018-05-26 22:00:00'
)
) item
);
更新的时候 where 语句必须 这样的写法,
否则 mysql 就会报错,因为 mysql 是不能 通过 查询 自身然后来进行 更新的。
报错内容:
MYSQL之You can't specify target table for update in FROM clause
参考地址: https://blog.csdn.net/z_youarethebest/article/details/53785487
上面的刚才我写的SQL语句, 是没有报错, 可是 执行更新之后, 更新的结果都 是 被更新为 null 了。
我这里是 mysql 5.6 不知道是不是 mysql的bug , 即没有报错,又被更新为 null 了。。。
原因是 因为 where src_order_item_id=isrc.id 这个语句, 在 mysql 中 是 获取 不到
订单明细表 里面的 src_order_item_id 这个字段内容的。
如果我们改为 :
where isrc.id=gwqmshop_process_order_item.src_order_item_id
mysql 就会报错了, 报错是因为 找不到 gwqmshop_process_order_item 表。
其实不管是 update 语句,还是 select 语句, 字段 通过 查询其他表,但是又需要更加当前查询的表的内容取管理的话,都是会报错的。
因为 最外层的表的内容传不去里面的 临时表的。
例子 :
SELECT i.id ,i.src_order_item_id,i.total_amount,i.total_weight,i.count * (
SELECT isrc.total_weight/isrc.count
from gwqmshop_process_order_item isrc where isrc.id =i.src_order