Select 来自 db table 1 的数据并将其插入另一个 db table 2 in php

Select data from db table 1 and insert it into another db table 2 in php

我有两个不同的数据库,名称:

  1. 数据库测试:Table 1
  2. dbtest2: Table 2

我想 select 从 dbtest Table 1 到 dbtest2 Table 2.

的所有数据和新条目

我试过了

$sqlfin = "INSERT INTO dbtest2.Table2 SELECT * FROM dbtest.Table1";
$resultfi = mysqli_query($db_conn, $sqlfin);

但到目前为止运气不好。我如何确保将新记录插入到 table 中?任何帮助将不胜感激?

INSERT INTO dbtest2 ( 
      id, 
      name, 
      status ) 
SELECT id, 
      name,          
       '1'
FROM dbtest
ORDER BY id ASC 

您可以使用 INSERT...SELECT 语法。请注意,您可以在 SELECT 部分直接引用 '1'。

针对您想要的任务尝试此查询:

首先查询 (创建Table与旧数据库完全相同,如果你没有):

CREATE TABLE dbtest2.Table2 LIKE dbtest.Table1;

Query Second (Insert all data to new created table) :

INSERT INTO dbtest2.Table2 SELECT * FROM dbtest.Table1;

让我们试试这个格式

INSERT INTO `dbtest2`.`Table2` SELECT * FROM `dbtest`.`Table1`

The following conditions hold for INSERT ... SELECT statements:

  • Specify IGNORE to ignore rows that would cause duplicate-key violations.
  • AUTO_INCREMENT columns work as usual.
  • To ensure that the binary log can be used to re-create the original tables, MySQL does not permit concurrent inserts for INSERT ... SELECT statements (see Section 8.11.3, “Concurrent Inserts”).
  • To avoid ambiguous column reference problems when the SELECT and the INSERT refer to the same table, provide a unique alias for each table used in the SELECT part, and qualify column names in that part with the appropriate alias.

INSERT ... SELECT Syntax


创建触发器: 用于添加新条目

CREATE TRIGGER copy_record BEFORE INSERT ON dbtest.Table1 
FOR EACH ROW 
BEGIN 
   INSERT INTO dbtest2.Table2 (first_name, last_name) VALUES (new.first_name, new.last_name); 
END

trigger_event indicates the kind of operation that activates the trigger. These trigger_event values are permitted:

INSERT: The trigger activates whenever a new row is inserted into the table; for example, through INSERT, LOAD DATA, and REPLACE

statements.

UPDATE: The trigger activates whenever a row is modified; for example, through UPDATE statements.

DELETE: The trigger activates whenever a row is deleted from the table; for example, through DELETE and REPLACE statements. DROP TABLE

and TRUNCATE TABLE statements on the table do not activate this trigger, because they do not use DELETE. Dropping a partition does not activate DELETE triggers, either.

CREATE TRIGGER Syntax

您的查询看起来是正确的,但如果这两个表的结构不同,查询就会失败。指定列以避免它,如:

INSERT INTO dbtest2.Table2 (2_col_1, 2_col_2) SELECT 1_col_1, 1_col_2 FROM dbtest.Table1


使用 PDO(另一种答案,我对 Mysqli 了解不多):
您可以使用 PDO 连接到 Mysql 而无需在使用多个 时提供数据库名称(但这是'强制),如:

$db = new PDO( "mysql:host=" . $host . ";", $user, $password, $options );

然后像制作 JOIN 一样写数据库名称、表和列(就像您所做的那样):用 .

分隔
// an example ..
$useDb = $db->query("INSERT INTO db_1.table1 (value_1, value_2) SELECT value_3, value_4 FROM db_2.table2 WHERE db_2.table2.id = 5");

(示例已测试且工作正常)