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

前端 未结 7 800
时光取名叫无心
时光取名叫无心 2020-12-12 23:48

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()

I would like to cop

7条回答
  •  失恋的感觉
    2020-12-12 23:59

    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. 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). $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. 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;$i0) {
                        $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);
            }
    

提交回复
热议问题