對於mysql的insert 大家是在熟悉不過了,但有相當一部分人(包括作者本人在寫這篇文章之前)只是對insert into table_name(col_name1,col_name2,……) values(value1,value2,……)比較熟悉,而對insert 的其他功能知之甚少,我們,先來看一下mysql的insert語法
1:
INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES (expression,...),(...),... or INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] SELECT ... or INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name SET col_name=expression, col_name=expression, ...
2:下面我通過一些實例來說明一下它的用法。
(1)建表
create table firsttb( id int auto_increment primary key, name varchar(20), age int, sex boolean );
(2):插入數據
一次插入多條
insert into firsttb(name,age,sex) values('aaa',10,0),('bbb',20,1),('ccc',30,1)
數據庫裏插入3條記錄。 insert into firsttb(name,age,sex) select name,age,sex from firsttb
將再次插入3條記錄。
我們還可以通過
insert into firsttb set name ='fff',age=50,sex=1
插入記錄
注意的問題
1:INSERT INTO table1(col1,col2,......) VALUES(值1,值2,......), (值1,值2,......)
就我所知,一次插入多條紀律的此SQL只能在mysql上用。它不是標準的sql語句。
2:mysql不支持insert all和inset----select union一次插入多條。 INTO tbl_nname (col1,col2) VALUES(col2*2,15); 因為:欄位 col1 的值先填入後,纔可以計算欄位 col2