简体   繁体   English

MYSQL:如何将整行从一个表复制到 mysql 中的另一个表,第二个表有一个额外的列?

[英]MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

I have two tables with identical structure except for one column... Table 2 has that additional column in which i would insert the CURRENT_DATE()我有两个结构相同的表,除了一列......表 2 有一个额外的列,我将在其中插入 CURRENT_DATE()

I would like to copy all the values from table1 to table2.我想将所有值从 table1 复制到 table2。

if i use如果我使用

INSERT INTO dues_storage SELECT * FROM dues WHERE id=5;

it throws an error pointing out to the difference in the number of columns.它抛出一个错误,指出列数的差异。

I have two questions on that:我有两个问题:

  1. How do I get around this?我该如何解决这个问题?
  2. and how do I add the value for the additional date column (CURRENT_DATE()) in table2 within this same statement?以及如何在同一语句中为 table2 中的附加日期列 (CURRENT_DATE()) 添加值?

To refine the answer from Zed, and to answer your comment:要完善 Zed 的答案,并回答您的评论:

INSERT INTO dues_storage
SELECT d.*, CURRENT_DATE()
FROM dues d
WHERE id = 5;

See TJ Crowder's comment见 TJ Crowder 的评论

The safest way to do it is to fully specify the columns both for insertion and extraction.最安全的方法是完全指定用于插入和提取的列。 There's no guarantee (to the application) that either of these will be the order you think they may be.不能保证(对应用程序)其中任何一个将是您认为它们可能的顺序。

insert into dues_storage (f1, f2, f3, cd)
    select f1, f2, f3, current_date() from dues where id = 5;

If you're worried about having to change many multiple PHP pages that do this (as you seem to indicate in the comment to another answer), this is ripe for a stored procedure.如果您担心必须更改许多执行此操作的多个 PHP 页面(正如您似乎在对另一个答案的评论中指出的那样),那么这对于存储过程来说已经成熟了。 That way, all your PHP pages simply call the stored procedure with (for example) just the ID to copy and it controls the actual copy process.这样,您的所有 PHP 页面只需使用(例如)要复制的 ID 调用存储过程,并控制实际的复制过程。 That way, there's only one place where you need to maintain the code, and, in my opinion, the DBMS is the right place to do it.这样,只有一个地方需要维护代码,而且在我看来,DBMS 是正确的地方。

INSERT INTO dues_storage
SELECT field1, field2, ..., fieldN, CURRENT_DATE()
FROM dues
WHERE id = 5;

Hope this will help someone... Here's a little PHP script I wrote in case you need to copy some columns but not others, and/or the columns are not in the same order on both tables.希望这会对某人有所帮助...这是我编写的一个小 PHP 脚本,以防您需要复制某些列而不是其他列,和/或两个表上的列顺序不同。 As long as the columns are named the same, this will work.只要列的名称相同,这将起作用。 So if table A has [userid, handle, something] and tableB has [userID, handle, timestamp], then you'd "SELECT userID, handle, NOW() as timestamp FROM tableA", then get the result of that, and pass the result as the first parameter to this function ($z).因此,如果表 A 具有 [userid, handle, something] 并且 tableB 具有 [userID, handle, timestamp],那么您将“SELECT userID, handle, NOW() as timestamp from tableA”,然后得到结果,并且将结果作为第一个参数传递给此函数 ($z)。 $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. $toTable 是您要复制到的表的字符串名称,而 $link_identifier 是您要复制到的数据库。 This is relatively fast for small sets of data.这对于小数据集来说相对较快。 Not suggested that you try to move more than a few thousand rows at a time this way in a production setting.不建议您尝试在生产环境中以这种方式一次移动超过几千行。 I use this primarily to back up data collected during a session when a user logs out, and then immediately clear the data from the live db to keep it slim.我主要使用它来备份在用户注销时在会话期间收集的数据,然后立即从实时数据库中清除数据以使其保持苗条。

 function mysql_multirow_copy($z,$toTable,$link_identifier) {
            $fields = "";
            for ($i=0;$i<mysql_num_fields($z);$i++) {
                if ($i>0) {
                    $fields .= ",";
                }
                $fields .= mysql_field_name($z,$i);
            }
            $q = "INSERT INTO $toTable ($fields) VALUES";
            $c = 0;
            mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
            while ($a = mysql_fetch_assoc($z)) {
                foreach ($a as $key=>$as) {
                    $a[$key] = addslashes($as);
                    next ($a);
                }
                if ($c>0) {
                    $q .= ",";
                }
                $q .= "('".implode(array_values($a),"','")."')";
                $c++;
            }
            $q .= ";";
            $z = mysql_query($q,$link_identifier);
            return ($q);
        }

Alternatively, you can use Inner Queries to do so.或者,您可以使用内部查询来执行此操作。

SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);

Hope this helps!希望这可以帮助!

SET @sql = 
CONCAT( 'INSERT INTO <table_name> (', 
    (
        SELECT GROUP_CONCAT( CONCAT('`',COLUMN_NAME,'`') ) 
            FROM information_schema.columns 
            WHERE table_schema = <database_name>
                AND table_name = <table_name>
                AND column_name NOT IN ('id')
    ), ') SELECT ', 
    ( 
        SELECT GROUP_CONCAT(CONCAT('`',COLUMN_NAME,'`')) 
        FROM information_schema.columns 
        WHERE table_schema = <database_name>
            AND table_name = <table_source_name>
            AND column_name NOT IN ('id')  
    ),' from <table_source_name> WHERE <testcolumn> = <testvalue>' );  

PREPARE stmt1 FROM @sql; 
execute stmt1;

Of course replace <> values with real values, and watch your quotes.当然用实际值替换 <> 值,并注意您的报价。

insert into target_table (column1,column2,column3,column4)
select column1,column2,column3,current_date()from source_table where id=xx

Just wanted to add this little snippet which works beautifully for me.只是想添加这个对我来说很好用的小片段。

INSERT INTO your_target_table SELECT * FROM your_rescource_table WHERE id = 18; INSERT INTO your_target_table SELECT * FROM your_resource_table WHERE id = 18;

And while I'm at it give a big shout out to Sequel Pro, if you're not using it I highly recommend downloading it...makes life so much easier当我在它的时候向 Sequel Pro 大喊大叫,如果你不使用它,我强烈建议你下载它......让生活变得更轻松

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在mysql中将整个行从一个表复制到另一个表,而第二个表具有修改后的字段 - How to copy an entire row from one table to another in mysql with the second table having a modified field 在MySQL触发器中将整个表从一个表复制到另一个表 - Copy entire row from one table to another in MYSQL trigger MySql中如何将列数据从一张表复制到另一张表? - How to Copy Column data from one table to another table in MySql? mysql-将整个行从一个表复制到另一个表,并在一个查询中添加带条件的count(*) - mysql - copy entire row to from one table to another and add count(*) with conditions in one query 使用带有字符串的额外列将数据从一个Mysql表传输到另一个 - Transfer data from one Mysql table to another with an extra column having a string 如何从另一个表更新MYSQL中的一个表? 具有额外的价值 - How to update one table in MYSQL from another table? with extra values 如何将一行从一个表移动到mysql中的另一个表? - How to move one row from one table, to another table in mysql? 将一列复制到另一张表中的mysql - Copy one column to another in different table mysql MySQL将colmn数据从一个表复制到另一行 - MySQL copy colmn data from one table to another row MySQL将具有多个NOT IN条件的行从一个表复制到另一个表 - MySQL copy row from one table to another with multiple NOT IN criteria
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM