MySQLテーブルレプリケーションinsert into構文の詳細について

1780 ワード

Web開発では、1つのテーブルのデータを別のテーブルに挿入する必要があり、インポートフィールドを指定する必要があり、インポート先テーブルに存在しないレコードを設定する必要があります.これらはプログラムで簡単なsqlに分割して実現できますが、1つのsqlを使用すると、多くのコードを節約できます.次にmysqlデータベースを例に挙げて説明します.
2枚の表:insertTestとinsertTest 2、前者にテストデータがあります
 
  
create table insertTest(id int(4),name varchar(12));
insert into insertTest values(100,‘liudehua');
insert into insertTest values(101,‘zhourunfa');
insert into insertTest values(102,‘zhouhuajian');

1.2枚のテーブルのフィールドが一致し、すべてのデータを挿入したい場合は、INSERT INTOターゲットテーブルSELECT*FROMソーステーブル;
 
  
insert into insertTest select * from insertTest2;

2.指定したフィールドのみをインポートする場合は、次の方法を使用します.
 
  
INSERT INTO ( 1, 2, …) SELECT 1, 2, … FROM ; 

フィールドの順序が一致している必要があります.
 
  
insert into insertTest2(id) select id from insertTest2;

3.ターゲット・テーブルに存在しないレコードのみをインポートする場合は、次の方法を使用します.
 
  
 INSERT INTO  
 ( 1, 2, …) 
 SELECT 1, 2, … 
 FROM  
 WHERE not exists (select * from  
 where . = . );

1>.複数のレコードを挿入:
 
  
insert into insertTest2
(id,name)
select id,name
from insertTest
where not exists (select * from insertTest2
where insertTest2.id=insertTest.id);

2>.レコードを挿入します.
 
  
insert into insertTest
(id, name)
SELECT 100, ‘liudehua'
FROM dual
WHERE not exists (select * from insertTest
where insertTest.id = 100);

テーブル名にdualを使用すると、select文の後に挿入するフィールドの値が直接続きます.