前置表准备

  1. CREATE TABLE product_insert
  2. (
  3. product_id CHAR(4) NOT NULL,
  4. product_name VARCHAR(100) not NULL,
  5. product_type VARCHAR(100) not NULL,
  6. sale_price INTEGER DEFAULT 0,
  7. purchase_price INTEGER ,
  8. regist_date date ,
  9. PRIMARY KEY (product_id)
  10. );
CREATE TABLE product_insert_copy
(
    product_id CHAR(4) NOT NULL,
    product_name VARCHAR(100) not NULL,
    product_type VARCHAR(100) not NULL,
    sale_price INTEGER DEFAULT 0,
    purchase_price INTEGER  ,
    regist_date date ,
    PRIMARY KEY (product_id)
);

insert基本用法

默认插入数据方式

-- 简单的插入数据 --
-- 语法 : insert into 表名 values(...) --
-- values内部顺序就是创建表的时候字段顺序 --
insert into product_insert values(0002,'外套','衣服',100,200,'2022-10-14');

对应字段插入数据方式

-- 对应字段插入数据方式 --
-- 语法:insert into table 表名  --
insert into product_insert 
(
  product_id,
  product_type,
  product_name,
  sale_price,
  purchase_price,
  regist_date
)
values (
  0003,
  '裤子',
  '喇叭裤',
  200,
  100,
  '2020-10-21'
)

-- 表名的字段名称与values内部数据一一对应 --

多条字段插入

insert into product_insert 
(
  product_id,
  product_type,
  product_name,
  sale_price,
  purchase_price,
  regist_date
)
values ( 0003,'裤子','喇叭裤',200,100,'2020-10-21'),
( 0004,'外套','程冠希卫衣',200,100,'2020-10-22' );

关于插入null

如果要插入null的话,就直接在对应数据书写数据为 null ,但是前提是建表的时候对应的字段不能是not null。

关于默认值的插入

建表的时候,我们首先就要进行默认值的设置(前提是插入的字段列数是有DEFAULT设置)

隐式默认值的插入

在对应字段插入中省去拥有默认值的字段,默认就给你进行了默认值的字段设置

显示默认值的插入

insert into product_insert 
values (
    0004,
    '默认值',
    'test',
    DEFAULT,
    200,
    '2018-10-25'
);

* 对应插入也一样,写入default *

如何选择选择

:::success 推荐显式插入,这样阅读代码起来会更加方便一点 :::

从别的表里面select 插入

上述建表中我们设置了两个表,因为product_insert 和 product_insert_copy字段完全能对应上, 我们可以直接讲查询的数据进行插入

insert into product_insert_copy
select * from product_insert;

如果字段不统一,我们可以对查询的数据进行名称修改后在插入

-- product_insert_copy 的结构就一个product_name --

insert into product_insert_copy (prodcuct_name)
select product_name from product_insert;

常见错误