SQL INSERT多行
许多开发人员经常问是否可能在单个语句中将多行插入单个表中。目前,当插入表中的值时,开发人员不得不编写多个插入语句。这不仅枯燥无聊,而且耗时。
让我们看几个实际的例子来更清楚地理解这个概念。我们将使用MySQL数据库来编写所有查询。
例1:
要在数据库中创建一个表,首先,我们需要选择我们要创建表的数据库。
mysql> USE dbs;
然后,我们将编写一个查询来在选定的数据库’dbs’中创建名为student的表。
mysql> CREATE TABLE student(ID INT, Name VARCHAR(20), Percentage INT, Location VARCHAR(20), DateOfBirth DATE);
学生表成功创建。
现在,我们将编写一个单一的查询语句来在学生表中插入多条记录:
mysql> INSERT INTO student(ID, Name, Percentage, Location, DateOfBirth) VALUES(1, "Manthan Koli", 79, "Delhi", "2003-08-20"), (2, "Dev Dixit", 75, "Pune", "1999-06-17"), (3, "Aakash Deshmukh", 87, "Mumbai", "1997-09-12"), (4, "Aaryan Jaiswal", 90, "Chennai", "2005-10-02"), (5, "Rahul Khanna", 92, "Ambala", "1996-03-04"), (6, "Pankaj Deshmukh", 67, "Kanpur", "2000-02-02"), (7, "Gaurav Kumar", 84, "Chandigarh", "1998-07-06"), (8, "Sanket Jain", 61, "Shimla", "1990-09-08"), (9, "Sahil Wagh", 90, "Kolkata", "1968-04-03"), (10, "Saurabh Singh", 54, "Kashmir", "1989-01-06");
为了验证在学生表中插入了多条记录,我们将执行SELECT查询。
mysql> SELECT *FROM student;
ID | Name | Percentage | Location | DateOfBirth |
---|---|---|---|---|
1 | Manthan Koli | 79 | Delhi | 2003-08-20 |
2 | Dev Dixit | 75 | Pune | 1999-06-17 |
3 | Aakash Deshmukh | 87 | Mumbai | 1997-09-12 |
4 | Aaryan Jaiswal | 90 | Chennai | 2005-10-02 |
5 | Rahul Khanna | 92 | Ambala | 1996-03-04 |
6 | Pankaj Deshmukh | 67 | Kanpur | 2000-02-02 |
7 | Gaurav Kumar | 84 | Chandigarh | 1998-07-06 |
8 | Sanket Jain | 61 | Shimla | 1990-09-08 |
9 | Sahil Wagh | 90 | Kolkata | 1968-04-03 |
10 | Saurabh Singh | 54 | Kashmir | 1989-01-06 |
根据结果显示,使用单个查询成功插入了全部十条记录。
示例2:
在数据库中创建表格,首先,我们需要选择要创建表格的数据库。
mysql> USE dbs;
然后我们将编写一个查询来在选定的数据库“dbs”中创建一个名为items_tbl的表。
mysql> CREATE TABLE items_tbl(ID INT, Item_Name VARCHAR(20), Item_Quantity INT, Item_Price INT, Purchase_Date DATE);
表名为items_tbl的表已成功创建。
现在,我们将编写一条单一的查询来向items_tbl表中插入多条记录:
mysql> INSERT INTO items_tbl(ID, Item_Name, Item_Quantity, Item_Price, Purchase_Date) VALUES(1, "Soap", 5, 200, "2021-07-08"), (2, "Toothpaste", 2, 80, "2021-07-10"), (3, "Pen", 10, 50, "2021-07-12"), (4, "Bottle", 1, 250, "2021-07-13"), (5, "Brush", 3, 90, "2021-07-15"), (6, "Notebooks", 10, 1000, "2021-07-26"), (7, "Handkerchief", 3, 100, "2021-07-28"), (8, "Chips Packet", 5, 50, "2021-07-30"), (9, "Marker", 2, 30, "2021-08-13"), (10, "Scissors", 1, 60, "2021-08-13");
为了验证在items_tbl表中插入了多条记录,我们将执行SELECT查询。
mysql> SELECT *FROM items_tbl;
ID | Item_Name | Item_Quantity | Item_Price | Purchase_Date |
---|---|---|---|---|
1 | Soap | 5 | 200 | 2021-07-08 |
2 | Toothpaste | 2 | 80 | 2021-07-10 |
3 | Pen | 10 | 50 | 2021-07-12 |
4 | Bottle | 1 | 250 | 2021-07-13 |
5 | Brush | 3 | 90 | 2021-07-15 |
6 | Notebooks | 10 | 1000 | 2021-07-26 |
7 | Handkerchief | 3 | 100 | 2021-07-28 |
8 | Chips Packet | 5 | 50 | 2021-07-30 |
9 | Marker | 2 | 30 | 2021-08-13 |
10 | Scissors | 1 | 60 | 2021-08-13 |
结果显示,使用单个查询成功插入了所有十条记录。