首先明白,insert,update,delete只能对单表
那么,要跨表更新怎么办呢,先通过连接(左连接,右连接,内连接)的方式生成临时表,对临时表进行操作
将下面括号内看成一张临时表
update (a left join b on a.id = b.a_id)
set expression = "a"
where b.measure_type='yx'
或者
update a,b
set expression = "a"
where (b.measure_type='yx' and a.id = b.a_id);
逗号连接,其实是内连接的简写 ,即 逗号 == inner join
outer join时,不要将where条件写入on中,如
update (a left join b on (a.id = b.a_id and b.measure_type='yx'))
set expression = "a"
on && where
sql中的连接查询分为3种, cross join,inner join,和outer join , 在 cross join和inner join中,筛选条件放在on后面还是where后面是没区别的,极端一点,在编写这两种连接查询的时候,只用on不使用where也没有什么问题。因此,on筛选和where筛选的差别只是针对outer join,也就是平时最常使用的left join和right join
outer join相对于inner join的一个主要特性就是以一侧的表为基础,所以,侧表的measure_type属性到临时表时值为null。
多表更新
UPDATE (product p
INNER JOIN productPrice pp
ON p.productId = pp.productId)
SET pp.price = pp.price * 0.8,
p.dateUpdate = CURDATE()
WHERE p.dateCreated < '2004-01-01'
上面的操作,能对俩张表进行更新,那是不是就意味着,刚开始说的只能对单表操作抵触了呢,并不是。
括号内看成一张临时表,俩张表进行了连接之后,p与pp都可以看作临时表的引用,只是多了个引用罢了。