MySQL: how to copy a table (including to another database)

Practice



Earlier I talked about how to move tables between databases .

MySQL: how to copy a table (including to another database)
Now let's look at how to copy a table: either just its structure, or its structure together with the data

It's easy too:

CREATE TABLE database2.mytable LIKE database1.mytable;
INSERT INTO database2.mytable SELECT * FROM database1.mytable;


This script copies the mytable table from database database1 to database database2. After the structure is copied (the first line), the data is copied (the second line).

As you might guess, if you don't need to copy the data, then you simply don't run the second line.

The same method can be used to copy tables within a single database.


PS. All of this is done in the MySQL administration console. That is, we go into the console:

$ mysql -u username -p

where instead of username you substitute the database user name (for example, root, which has maximum privileges and has existed since the DBMS was born). If we're talking about Windows, then run the corresponding utility from the "Start" menu.

MySQL 5.x+,

MySQL 7.x+,
MySQL 8.x+,

Comments

Евгений 21-07-2021
CREATE TABLE database1.mytable LIKE database2.mytable;

INSERT INTO database2.mytable SELECT * FROM database1.mytable;

Первая команда создаст в первой базе таблицу аналогичную как во второй базе а потом вторую наполнит тем что создало. Поменяйте местами ссылки на базы в первой команде.
Admin 22-07-2021
спасибо исправили

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Databases - MySql (Maria DB)"

Terms: Databases - MySql (Maria DB)