sql里面插入语句insert后面的values关键字可省略

转载于:https://blog.csdn.net/lycIT/article/details/80598517


值是可以省略的


插入到表名(列值)后跟一个查询语句的话就代表值,简单的说就是后面select select出来的值就是要插入的值,即  
insert into tb(字段名一,字段名二)select 字段名一字段名二 from tb 

等于
insert into tb(字段名一字段名二)values(查出的字段值一,查出来的字段值一);

例子:插入一行ID = 3,名字=丁老师,薪水= 5000的记录

  1. insert into teacher(id,name,salary)
  2. select 3, '丁老师', 5000 from teacher
  3. where not exists( select * from teacher where id= 3) limit 1;

或者

  1. insert into teacher(id,name,salary)
  2. ( select 4,'白老师',4000 from teacher
  3. where not exists(select * from teacher where id=4) limit 1);
  1. 在上面的SQL语句中:执行的原理解析:
  2. 若teacher表中不存在id=3的那条记录,则生成要插入表中的数据并插入表;
  3. 若teacher表中存在id=3的那条记录,则不生成要插入表中的数据。
  4. 其实程序可以分开看:
  5. select * from teacher where id=3 若查询有值,则表示真,即存在id=3这条记录,若查询没有值则表示假,即不存在id=3这条记录,
  6. ②若果不存在id=3这条记录,那么又因为 not exists 本身表示假,即不存在的意思;假假为真,所以此时程序可以形象的理解为
  7. select 3,'丁老师',5000 from teacher where not exists (false) limit 1;
  8. 等价于
  9. select 3,'丁老师',5000 from teacher where true limit 1;
  10. ③所以程序就会生成一行为 3,'丁老师',5000的记录
  11. ④最后生成的数据就会插入表中

CREATE  TABLE  tb ( a  int ,  b   int  );
 
-- 一次插入一行数据的写法: 必须要有  VALUES
INSERT  INTO  tb  VALUES (1,  2);
INSERT  INTO  tb  VALUES (1,  3);
GO
 
 
-- 一次插入一行或者多行数据的写法: 必须要有  SELECT
INSERT  INTO  tb  SELECT   2, 1;
 
INSERT  INTO  tb 
SELECT   3, 1   UNION  ALL
SELECT   3, 2   UNION  ALL
SELECT   3, 3;
GO
 
 
-- 核对数据
SELECT  FROM  tb
GO
 
a           b
----------- -----------
           1           2
           1           3
           2           1
           3           1
           3           2
           3           3
 
(6 行受影响)


批量判重插入

  1. <sql id="Base_Column_List1" >
  2. uuid, systemName, enviromentType, jobOrderNum, jobName, executeTime, jobLogAddress, status
  3. </sql>
  4. <insert id="insertDatas" parameterType="cn.lz.devops.model.DataCollectionJobInfo" >
  5. insert into data_collection_job_info
  6. <trim prefix="(" suffix=")" suffixOverrides="," >
  7. <include refid="Base_Column_List1" />
  8. </trim>
  9. <foreach collection="list" item="item" separator="UNION ALL" close=";">
  10. <trim prefix="(" suffix=")" suffixOverrides="UNION ALL" >
  11. select
  12. <trim suffixOverrides="," >
  13. #{item.uuid,jdbcType=VARCHAR},
  14. #{item.systemName,jdbcType=VARCHAR},
  15. #{item.enviromentType,jdbcType=VARCHAR},
  16. #{item.jobOrderNum,jdbcType=INTEGER},
  17. #{item.jobName,jdbcType=VARCHAR},
  18. #{item.executeTime,jdbcType=VARCHAR},
  19. #{item.jobLogAddress,jdbcType=VARCHAR},
  20. #{item.status,jdbcType=INTEGER}
  21. </trim>
  22. from data_collection_job_info
  23. where not exists(select * from data_collection_job_info where uuid=#{item.uuid, jdbcType=VARCHAR}) limit 1
  24. </trim>
  25. </foreach>
  26. </insert>


into 也可以省略



猜你喜欢

转载自blog.csdn.net/qq_28817739/article/details/80910471