INSERT INTO
用于向表中插入数据,遇到主键重复时会自动忽略当前写入数据,不做更新,作用等同于INSERT IGNORE INTO
。
语法
INSERT [IGNORE]
INTO table_name
[( column_name [, …] )]
[VALUES]
[(value_list[, …])]
[query];
参数
IGNORE
:可选参数,若系统中已有相同主键的记录,新记录不会被写入。column_name
:可选参数,列名。query
:通过定义查询,将一行或多行数据插入表中。
注意事项
如果插入数据时不指定列名,则要插入的数据必须和CREATE TABLE语句中声明的列的顺序一致。
示例
创建CUSTOMER和COURSES表。
CREATE TABLE customer (
customer_id bigint NOT NULL COMMENT '顾客ID',
customer_name varchar NOT NULL COMMENT '顾客姓名',
phone_num bigint NOT NULL COMMENT '电话',
city_name varchar NOT NULL COMMENT '所属城市',
sex int NOT NULL COMMENT '性别',
id_number varchar NOT NULL COMMENT '身份证号码',
home_address varchar NOT NULL COMMENT '家庭住址',
office_address varchar NOT NULL COMMENT '办公地址',
age int NOT NULL COMMENT '年龄',
login_time timestamp NOT NULL COMMENT '登录时间',
PRIMARY KEY (login_time,customer_id,phone_num)
)
DISTRIBUTED BY HASH(customer_id)
PARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m%d')) LIFECYCLE 30
COMMENT '客户信息表';
CREATE TABLE courses(
id bigint AUTO_INCREMENT PRIMARY KEY,
name varchar(20) NOT NULL,
grade varchar(20) default '三年级',
submission_date timestamp
)
DISTRIBUTED BY HASH(id)
向CUSTOMER表中插入一条数据。
INSERT INTO customer(customer_id,customer_name,phone_num,city_name,sex,id_number,home_address,office_address,age,login_time) values (002367,'杨过','13900001234','杭州',0,'987300','西湖','转塘云栖小镇',23,'2018-03-02 10:00:00');
使用
INSERT INTO ... ON DUPLICATE KEY UPDATE...
向CUSTOMER表中插入一条数据。INSERT INTO customer values (002367,'杨过','13900001234','杭州',0,'987300','西湖','转塘云栖小镇',23,'2018-03-02 10:00:00'); ON DUPLICATE KEY UPDATE age=23;
向CUSTOMER表中插入多条数据。
INSERT INTO customer(customer_id,customer_name,phone_num,city_name,sex,id_number,home_address,office_address,age,login_time) values (002367,'李四','13900001234','杭州',0,'987300','西湖','转塘云栖小镇',23,'2018-03-02 10:00:00'),(002368,'张三','13900001111','杭州',0,'987300','西湖','转塘云栖小镇',28,'2018-08-01 11:00:00'),(002369,'王五','13900002222','杭州',1,'987300','西湖','转塘云栖小镇',35,'2018-09-12 08:11:00');
向CUSTOMER表中插入多条数据时,可以省略列名。
INSERT INTO customer values (002367,'李四','13900001234','杭州',0,'987300','西湖','转塘云栖小镇',23,'2018-03-02 10:00:00'),(002368,'张三','13900001111','杭州',0,'987300','西湖','转塘云栖小镇',28,'2018-08-01 11:00:00'),(002369,'王五','13900002222','杭州',1,'987300','西湖','转塘云栖小镇',35,'2018-09-12 08:11:00');
向COURSES表中插入一条数据。
INSERT INTO courses (name,submission_date) values("Jams",NOW());
INSERT query
示例请参见INSERT SELECT FROM。
文档内容是否对您有帮助?