technology-note/数据库/基础/1.mysql使用查询结果进行插入操作.md
2022-01-20 16:33:50 +08:00

90 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
id: "2019-01-25-09-48"
date: "2019/01/25 09:48"
title: "mysql使用查询结果进行插入操作"
tags: ["mysql","select","insert"]
categories:
- "数据库"
- "分布式事务"
---
  经常在使用 mysql 的过程中想要从一张表中查出一些数据插入到另一张表中,操作如下。
# 1、方法
  使用 insert ... select ...操作。要求两边参数个数,参数类型完全一致,所以如果不一致就需要进行一些转换操作来让它一致。例子如下:
  从表 B 中查数据插入到表 A 中。
1. A 表字段多B 表字段少
```javascript
//A表结构
A:{
a:int,
b:int,
c:int
}
//B表结构
B:{
a:int,
b:int
}
```
sql 语句如下:
```sql
insert into A(a,b,c) select b.*,1 from B b;
```
  由于 B 表比 A 表少了一个 int 型参数 c所以在 select 语句中加上一个数值补齐。
<!-- more -->
2. A 表字段少B 表字段多
```javascript
A:{
a:int,
b:int
}
B:{
a:int,
b:int,
c:int
}
```
sql 语句如下:
```sql
insert into A(a,b) select a,b from B
```
&emsp;&emsp;A 表只有两个 int 参数,所以只能从 B 中 select 两个参数,不一定是 a,b。也可以是 a,c 只要参数类型,个数一致就行。
3. AB 表字段一致,但是类型不一致
```javascript
//A表结构
A:{
a:int,
b:int
}
//B表结构
B:{
a:string,
b:int
}
```
sql 语句如下:
```sql
insert into A(a,b) select (cast a as SIGNED),b from B
```
&emsp;&emsp;使用类型转换将参数类型转换为一致即可。