74

構造が同一の 2 つのテーブルがある場合、1 つのテーブルから別のテーブルに一連の行を移動するにはどうすればよいですか?

行のセットは、選択クエリから決定されます。

例えば:

customer table

person_id | person_name | person_email
123         tom           tom@example.com


persons table

person_id | person_name  | person_email

サンプルの選択は次のようになります。

select * from customer_table where person_name = 'tom';

行を customer テーブルから person テーブルに移動したい

元のテーブルからデータを削除するのが理想的ですが、これは取引を妨げるものではありません。

4

7 に答える 7

136

シンプルなINSERT INTO SELECTステートメント:

INSERT INTO persons_table SELECT * FROM customer_table WHERE person_name = 'tom';

DELETE FROM customer_table WHERE person_name = 'tom';
于 2013-11-06T20:11:32.817 に答える
39
    INSERT INTO Persons_Table (person_id, person_name,person_email)
          SELECT person_id, customer_name, customer_email
          FROM customer_table
          WHERE "insert your where clause here";
    DELETE FROM customer_table
          WHERE "repeat your where clause here";
于 2013-11-06T20:12:00.587 に答える
32

Fabioの答えは本当に良いですが、実行時間がかかります(Trilarionがすでに書いているように)

実行が高速な別のソリューションがあります。

START TRANSACTION;
set @N := (now());
INSERT INTO table2 select * from table1 where ts < date_sub(@N,INTERVAL 32 DAY);
DELETE FROM table1 WHERE ts < date_sub(@N,INTERVAL 32 DAY);
COMMIT;

@N は、開始時にタイムスタンプを取得し、両方のコマンドに使用されます。誰も邪魔しないように、すべてがトランザクション内にあります

于 2015-07-01T09:02:02.150 に答える
6
INSERT INTO Persons_Table (person_id, person_name,person_email)
      SELECT person_id, customer_name, customer_email
      FROM customer_table
      ORDER BY `person_id` DESC LIMIT 0, 15 
      WHERE "insert your where clause here";
DELETE FROM customer_table
      WHERE "repeat your where clause here";

ORDER BY、LIMIT、および ASC/DESC を使用して、移動する特定の列を制限および選択することもできます。

于 2015-07-29T04:13:05.933 に答える