简体   繁体   中英

Dump values from a table to another one in MySQL

Say I have a table called dogs that have the following columns:

id, fk_hospital, fk_owner, date, name

And I want to create another table that will have the following columns:

fk_hospital, fk_owner, fk_dogs, what_type

In this second table fk_dogs will be the id of the first table. And what_type by default will be NULL.

So basically, I want to dump from the first table to the second table. The create table of the second table looks like this:

CREATE TABLE dogs_info (
fk_hospital char(4) NOT NULL,
fk_owner char(11) NOT NUL,
fk_dogs int(11) unsigned NOT NULL,
what_type tinyint(1) unsigned DEFAULT NULL,
PRIMARY KEY(fk_hospital, fk_owner, fk_dogs)
)

How could I dump the content from the first to the second? Do I need any server language, like PHP? Or I can do it straight with mysql?

EDIT: I want to do this by chunks, so first do the dump for a particular fk_hospital and fk_owner, and then for next fk_owner. Can this be done with MySQL too?

您可以使用MySQL:

INSERT INTO dogs_info SELECT fk_hospital, fk_owner, id, NULL FROM dogs

use INSERT INTO..SELECT statement

INSERT INTO dogs_info(k_hospital, fk_owner, fk_dogs)
SELECT fk_hospital, fk_owner, ID as fk_dogs
FROM dogs

You can try this select and while loop

$result = $mysqli->query('select fk_hospital, fk_owner from dogs');
while ($row = $result->fetch_assoc()) {
    $mysqli->query('insert into dogs_info ' .
                   '(fk_hospital, fk_owner, fk_dogs) ' .
                   'select fk_hospital, fk_owner, id ' .
                   'from dogs ' .
                   'where fk_hospital = ' . $row['fk_hospital'] .
                   ' and ' . $row['fk_owner']);
}

No need of PHP .

INSERT INTO dogs_info(fk_hospital, fk_owner, fk_dogs)
SELECT fk_hospital,fk_owner,id
FROM dogs

See INSERT INTO ... SELECT

For inserting in chunks use ORDER BY clause

 INSERT INTO dogs_info(fk_hospital, fk_owner, fk_dogs)
    SELECT fk_hospital,fk_owner,id
    FROM dogs
    ORDER BY fk_hospital,fk_owner

See ORDER BY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM