mysql insert into select from和update select举例概述

开发中为了减少访问数据库,可以将查询结果插入到另一张表中的操作简化成一步,也就需要用到insert into select from语句。

这里举个例子:

insert into t_3(id,name,count) 
select t.id,t.name,t.count from (
select a.code as id,b.name as name,b.count as count from t_1 a,t_2 b where b.id = 1
) t

同理,将查询结果更新到另一张表的操作也可简化成一步,不过和insert稍有不同。

举例:

update t_product inner join (select pid,count from t_cart) t on id=t.pid 
set amount=amount-t.count

inner join(等值连接) 只返回两个表中联结字段相等的行

猜你喜欢

转载自blog.csdn.net/wl_Honest/article/details/82385421