MySQL
 Computer >> コンピューター >  >> プログラミング >> MySQL

MySQLでINSERTINTOSELECTとUNIONを使用して複数の挿入を実行します


複数の挿入を実行するための構文は次のとおりです-

insert into yourTableName(yourColumnName1,yourColumnName2,yourColumnName3,..N)
   select yourValue1 as yourColumnName1,yourValue2 as yourColumnName2,yourValue3 as yourColumnName3,......N
   union
   select yourValue1 as yourColumnName1,yourValue2 as yourColumnName2,yourValue3 as yourColumnName3,......N
.
.
N

上記の構文を理解するために、テーブルを作成しましょう-

mysql> create table DemoTable1936
   (
   StudentId int,
   StudentName varchar(20),
   StudentCountryName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

挿入コマンド-

を使用して、テーブルにいくつかのレコードを挿入します
mysql> insert into DemoTable1936(StudentId,StudentName,StudentCountryName)
   select 1001 as StudentId,'Chris' as StudentName,'US' as StudentCountryName
   union
   select 1002 as StudentId,'Robert' as StudentName,'UK' as StudentCountryName
   union
   select 1003 as StudentId,'David' as StudentName,'AUS' as StudentCountryName;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

selectステートメントを使用してテーブルのすべてのレコードを表示する-

mysql> select * from DemoTable1936;

これにより、次の出力が生成されます-

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
|      1001 | Chris       |               US   |
|      1002 | Robert      |               UK   |
|      1003 | David       |              AUS   |
+-----------+-------------+--------------------+
3 rows in set (0.00 sec)

  1. MySQL INSERT INTO SELECTを、AUTO_INCREMENTを使用してテーブルに挿入します

    テーブルを作成しましょう- mysql> create table DemoTable1923    (    UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,    UserName varchar(20)    ); Query OK, 0 rows affected (0.00 sec) 挿入コマンド-を使用して、テーブルにいくつかのレコードを挿入します mysql> insert into DemoTable1923(UserId,UserName

  2. MySQLテーブルで先行ゼロの値を選択して挿入します

    このために、LPAD()とともにINSERTINTOSELECTステートメントを使用できます。まずテーブルを作成しましょう- mysql> create table DemoTable1967    (    Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,    UserId varchar(20)    ); Query OK, 0 rows affected (0.00 sec) 挿入コマンド-を使用して、テーブルにいくつかのレコードを挿入します mysql>