转载于:https://blog.csdn.net/lycIT/article/details/80598517
值是可以省略的
插入到表名(列值)后跟一个查询语句的话就代表值,简单的说就是后面select select出来的值就是要插入的值,即
insert into tb(字段名一,字段名二)select 字段名一,字段名二 from tb
等于
insert into tb(字段名一,字段名二)values(查出的字段值一,查出来的字段值一);
例子:插入一行ID = 3,名字=丁老师,薪水= 5000的记录
-
insert into teacher(id,name,salary)
-
select 3, '丁老师', 5000 from teacher
-
where not exists( select * from teacher where id= 3) limit 1;
或者
-
insert into teacher(id,name,salary)
-
( select 4,'白老师',4000 from teacher
-
where not exists(select * from teacher where id=4) limit 1);
-
在上面的SQL语句中:执行的原理解析:
-
若teacher表中不存在id=3的那条记录,则生成要插入表中的数据并插入表;
-
若teacher表中存在id=3的那条记录,则不生成要插入表中的数据。
-
-
其实程序可以分开看:
-
① select * from teacher where id=3 若查询有值,则表示真,即存在id=3这条记录,若查询没有值则表示假,即不存在id=3这条记录,
-
-
②若果不存在id=3这条记录,那么又因为 not exists 本身表示假,即不存在的意思;假假为真,所以此时程序可以形象的理解为
-
select 3,'丁老师',5000 from teacher where not exists (false) limit 1;
-
等价于
-
select 3,'丁老师',5000 from teacher where true limit 1;
-
-
③所以程序就会生成一行为 3,'丁老师',5000的记录
-
-
④最后生成的数据就会插入表中
-- 一次插入一行数据的写法: 必须要有 VALUES
-- 一次插入一行或者多行数据的写法: 必须要有 SELECT
INSERT
INTO
tb
SELECT
3, 2
UNION
ALL
SELECT
3, 3;
-- 核对数据
SELECT
*
FROM
tb
a b
----------- -----------
1 2
1 3
2 1
3 1
3 2
3 3
(6 行受影响)
批量判重插入
-
<sql id="Base_Column_List1" >
-
uuid, systemName, enviromentType, jobOrderNum, jobName, executeTime, jobLogAddress, status
-
</sql>
-
-
<insert id="insertDatas" parameterType="cn.lz.devops.model.DataCollectionJobInfo" >
-
insert into data_collection_job_info
-
<trim prefix="(" suffix=")" suffixOverrides="," >
-
<include refid="Base_Column_List1" />
-
</trim>
-
<foreach collection="list" item="item" separator="UNION ALL" close=";">
-
<trim prefix="(" suffix=")" suffixOverrides="UNION ALL" >
-
select
-
<trim suffixOverrides="," >
-
#{item.uuid,jdbcType=VARCHAR},
-
#{item.systemName,jdbcType=VARCHAR},
-
#{item.enviromentType,jdbcType=VARCHAR},
-
#{item.jobOrderNum,jdbcType=INTEGER},
-
#{item.jobName,jdbcType=VARCHAR},
-
#{item.executeTime,jdbcType=VARCHAR},
-
#{item.jobLogAddress,jdbcType=VARCHAR},
-
#{item.status,jdbcType=INTEGER}
-
</trim>
-
from data_collection_job_info
-
where not exists(select * from data_collection_job_info where uuid=#{item.uuid, jdbcType=VARCHAR}) limit 1
-
</trim>
-
</foreach>
-
</insert>
into 也可以省略