INSERT INTO tb_name (col1, col2, ...) VALUES (val1, val2, ...)[,(val1, val2, ...),...]
字符型:單引號
數值型:不需要引號
日期時間型:不需要引號
空值:NULL,不能寫成 ''
如向tutors表插入兩行數據:
mysql> INSERT INTO tutors(Tname,Gender,Age) VALUES('Sam','M',28),('Barlow','M',27);
Query OK, 2 rows affected (0.03 sec)
Records: 2 Duplicates: 0 Warnings: 0
INSERT INTO tb_name SET col_name={expr | DEFAULT}, ...
如向tutors表插入一行數據:
mysql> INSERT INTO tutors SET Tname='Winne',Gender='F',Age=25;
Query OK, 1 row affected (0.04 sec)
INSERT [INTO] tbl_name [(col_name,...)] SELECT ...
如下將students表中Age大於20的插入到tutors表中:
mysql> SELECT Name,Gender,Age FROM students WHERE Age > 20;
+-------------+--------+------+
| Name | Gender | Age |
+-------------+--------+------+
| DingDian | M | 25 |
| HuFei | M | 31 |
| Xuzhu | M | 26 |
| LingHuchong | M | 22 |
+-------------+--------+------+
4 rows in set (0.19 sec)mysql> INSERT INTO tutors(Tname,Gender,Age) SELECT Name,Gender,Age FROM students WHERE Age > 20;
Query OK, 4 rows affected (0.09 sec)
Records: 4 Duplicates: 0 Warnings: 0
使用INSERT插入數據時,如果違反約束,會導致插入失敗。如students表要求Name字段不能相同,那使用INSERT插入已經存在的Name時,就會失敗。使用REPLACE插入數據,可以在此種情況下,使用新數據替換原數據,而如果不違反約束關系,則與INSERT一樣正常插入數據。
方法一:
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
[PARTITION (partition_name,...)]
[(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
方法二:
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
方法三:
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
[PARTITION (partition_name,...)]
[(col_name,...)]
SELECT ...