mysql多表关联更新


本文摘自PHP中文网,作者(*-*)浩,侵删。

本文分享下,在mysql中实现多表关联更新update的方法,分享一些常用的update多表更新的例子,供大家学习参考。

推荐课程:MySQL教程。

创建以下的简单模型,并构造部分测试数据:
在某个业务受理子系统BSS中,

1

2

3

4

5

6

7

8

9

--客户资料表

create table customers

(

customer_id number(8) not null, -- 客户标示

city_name varchar2(10) not null, -- 所在城市

customer_type char(2) not null, -- 客户类型

...

)

create unique index PK_customers on customers (customer_id)

由于某些原因,客户所在城市这个信息并不什么准确,但是在客户服务部的CRM子系统中,通过主动服务获取了部分客户20%的所在城市等准确信息,于是你将该部分信息提取至一张临时表中:

1

2

3

4

5

6

create table tmp_cust_city

(

customer_id number(8) not null,

citye_name varchar2(10) not null,

customer_type char(2) not null

)

1) 最简单的形式

1

2

3

4

5

--经确认customers表中所有customer_id小于1000均为'北京'

--1000以内的均是公司走向全国之前的本城市的老客户:)

update customers

set city_name='北京'

where customer_id<1000

2) 两表(多表)关联update -- 仅在where字句中的连接

1

2

3

4

5

6

7

--这次提取的数据都是VIP,且包括新增的,所以顺便更新客户类别

update customers a -- 使用别名

set customer_type='01' --01 为vip,00为普通

where exists (select 1

from tmp_cust_city b

where b.customer_id=a.customer_id

)

3) 两表(多表)关联update -- 被修改值由另一个表运算而来

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

update customers a -- 使用别名

set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)

where exists (select 1

from tmp_cust_city b

where b.customer_id=a.customer_id

)

-- update 超过2个值

update customers a -- 使用别名

set (city_name,customer_type)=(select b.city_name,b.customer_type

from tmp_cust_city b

where b.customer_id=a.customer_id)

where exists (select 1

from tmp_cust_city b

where b.customer_id=a.customer_id

)

注意在这个语句中,

1

2

3

4

5

6

7

8

9

(select b.city_name,b.customer_type

from tmp_cust_city b

where b.customer_id=a.customer_id

)

(select 1

from tmp_cust_city b

where b.customer_id=a.customer_id

)

是两个独立的子查询,查看执行计划可知,对b表/索引扫描了2篇;

阅读剩余部分

相关阅读 >>

mysql怎么查询日期中的月份

mysql 8.0中有什么新功能

mysql容器之间的replication配置实例详解

怎么设置mysql的环境变量

美团网技术团队分享的mysql索引及慢查询优化教程

mysql子查询的详细介绍

使用mysql在终端执行sql并把结果写入文件的方法

mysql中常用指令操作的介绍(代码示例)

怎么给mysql添加值?

mysql数据表的基本操作之表结构操作,字段操作实例分析

更多相关阅读请进入《mysql》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...