[英]running update statment with Where condition on same table
我有一个项目表:
itemid quantity unitid baseunitid
880 5 10 null
881 5 5 null
单位表:
unitid unittypeid
10 1
5 1
4 1
假设10是KM,5是米,4是厘米。
单位类型表:
unittypeid baseunitid
1 4
这意味着unittypeid 1包含一组长度单位,它们在我的系统中的基本单位是unitid=4
,即cm
。
我想写这传过来的查询items
,并更新basunit
列的基本单元为出现在baseunitid
。
我想得到的意思是:
itemid quantity unitid baseunit
10 5 10 4
11 5 5 4
我写了这个查询:
update items a set baseunitid = (select baseunitid
from unittypes
where unittypeid=(select unittypeid
from units
where unitid=a.unitid)
但是,这不起作用,因为我无法在子查询中引用a.unitid
。
我该如何解决?
您可以使用FROM
子句执行此操作:
update items i
set baseunitid = ut.baseunitid
from units u join
unittypes ut
on ut.unittypeid = u.unittypeid
where i.unitid = u.unitid;
但是,我建议您不要将此信息保存在两个表中。 而是,使用查询,视图或函数来提取信息。 如果基本单位发生变化,这将防止出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.