- Копирование записей из одной таблицы в другую MySQL
- Частичное копирование
- Полное копирование
- Подгонка структуры таблицы
- Копирование с подзапросом в третью таблицу
- Копирование записей из двух и более таблиц
- Скопировать таблицу из одной БД в другую mysql + php
- Copy a MySQL table using PHP.
- Copy one mysql database table to another using PHP
- MYSQL copy one table to another SYNTAX
- Copy one mysql table data to another mysql table using id
- Copy one table to another usind id
Копирование записей из одной таблицы в другую MySQL
Примеры SQL-запросов для копирования записей из разных таблицы.
Частичное копирование
К примеру есть две одинаковые по структуре, нужно из таблицы `table_a` скопировать запись с определенными полями в таблицу `table_b`.
INSERT INTO `table_a` (`name`, `alt`, `page`) SELECT `name`, `alt`, `page` FROM `table_b` WHERE `id` = 1
Копирование нескольких записей:
INSERT INTO `table_a` (`name`, `alt`, `page`) SELECT `name`, `alt`, `page` FROM `table_b` WHERE `id` IN(1,2,3)
Полное копирование
Если таблицы `table_a` и `table_b` полностью одинаковые по структуре, то названия полей можно опустить.
INSERT INTO `table_b` SELECT * FROM `table_a`
Или указать только нужные поля:
INSERT INTO `table_a` (`name`, `alt`, `page`) SELECT `name`, `alt`, `page` FROM `table_b`
Подгонка структуры таблицы
Если таблицы разные по структуре, то можно подогнать названия и значения полей.
INSERT INTO `table_b` (`name`, `alt`, `page`, `module`, `sort`) SELECT `filename` AS `name`, '' AS `alt`, `page`, 'prod' AS `module`, 1 AS `sort` FROM `table_a`
Копирование с подзапросом в третью таблицу
INSERT INTO `table_b` (`name`, `alt`, `page`, `module`, `sort`) SELECT (SELECT `name` FROM `table_c` WHERE `item_id` = `table_a`.`id`) AS `name`, '' AS `alt`, `page`, 'prod' AS `module`, 1 AS `sort` FROM `table_a`
Копирование записей из двух и более таблиц
INSERT INTO `table_b` (`name`, `email`, `address`) SELECT * FROM ( (SELECT `name`, `email`, `address` FROM `table_a`) UNION ( SELECT `name`, `email`, `address` FROM `table_c`) )
Скопировать таблицу из одной БД в другую mysql + php
Сообщение от dkv01
Здравствуйте. Помогите составить запрос.
Нужно скопировать таблицу из одной БД в другую.
Пробовал так:
$db = mysqli_query("INSERT INTO db2.table SELECT * FROM db1.table")
$db2->query("CREATE TABLE db2.table LIKE db1.table"); $db2->query("INSERT INTO db2.table SELECT * FROM db1.table");
Скопировать запись из одной ячеки в другую талицу
Помогите пожалуйста составить запрос. Суть такая нужно одним запросом скопировать id ячейки.
Копирование данных из одной таблицы в другую (MySQL)
Здравствуйте, как из одной заполненной таблицы скопировать значения (не все) и заполнить другую.
В одной таблице несколько ссылок на другую таблицу
В схеме БД существует связь между таблицами ВидыПолисов и Риски, когда ВидыПолисов имеет несколько.
Сообщение от dkv01
Сообщение от YuryK
А говорили «не работает»
А теперь во-второй раз работать не будет
Ну так синтаксис же не правильный был, ну или mysql_select_db нужно было добавить
Почему второй раз работать не будет ?
CREATE TABLE db2.table при существующей таблице работает? Странно Почему бы тогда копированию при несуществующей тоже не работать?
Добавлено через 1 минуту
Сообщение от dkv01
INSERT INTO db2.table SELECT * FROM db1.table INSERT INTO db2.table SELECT * FROM db1.table
Сообщение от YuryK
CREATE TABLE db2.table при существующей таблице работает? Странно Почему бы тогда копированию при несуществующей тоже не работать?
Добавлено через 1 минуту
INSERT INTO db2.table SELECT * FROM db1.table INSERT INTO db2.table SELECT * FROM db1.table
Для этого делается проверка существующих таблиц.
Если таблица с таким имени существует то к имени создаваемой таблице добавляется идентификатор.
Вообщем цель — резервное копирование таблицы, перед обновлением, с определенным количеством копий.
Скопировать id с одной таблицы на другую таблицу другую форму
Добрый день! Подскажите, как и где написать,чтобы id с одной таблицы скопировался в другую таблицу.
Скопировать таблицу из одной БД в другую БД
Доброго времени суток. Я расширил свою программу и случилось так что все нужные данные находятся в.
Как программно скопировать таблицу из одной базы в другую
как программно скопировать таблицу из одной базы в другую? есть 2 базы: 1.mdb и 2.mdb в 1ой базе.
Скопировать все строки из определенных полей одной таблицы в другую таблицу
Имеются 2 таблицы: ADOTable1 ADOTable6 Нужно скопировать все строки из полей AAA, BBB, CCC.
Copy a MySQL table using PHP.
This is a short guide on how to copy a MySQL table using PHP. In this post, we will be using the PDO object.
Take a look at the following code sample:
//Connect to MySQL using PDO. $pdo = new PDO($dsn, $user, $password); //The name of the table that you want to copy. $currentTable = 'members'; //The name of the new table. $newTableName = 'members_copy'; //Run the CREATE TABLE new_table LIKE current_table $pdo->query("CREATE TABLE $newTableName LIKE $currentTable"); //Import the data from the old table into the new table. $pdo->query("INSERT $newTableName SELECT * FROM $currentTable");
A drill-down of the PHP above:
- We connected to MySQL using the PDO object.
- The name of the table that we want to copy is called “members”.
- The name of the new table that we want to copy our structure and data over to is called “members_copy”.
- We copied the structure of our old table by using the SQL statement: CREATE TABLE new_table_name LIKE current_table_name. This creates a MySQL table that is an exact replica of the old table. In other words, any indexes or triggers will also be copied over to the new table structure.
- Finally, we imported the data from the old table into the new copied table.
If you do not want to copy the indexes and triggers, then you can use the following SQL statement:
CREATE TABLE new_table_name AS SELECT * FROM current_table_name;
If you want to verify that your new table has been copied over, you can check out my guide on how to list the tables in a MySQL database using PHP and the PDO object.
Hopefully, you found this guide useful.
Copy one mysql database table to another using PHP
You can copy one table to another using an MYSQL query and PHP script. if you are working on a PHP project and you want to copy a table data to another using MYSQL and PHP then you have done it by myself insert and select query. Think about the update operation in php. How we can get the data from the database user id. If we click id 1 that shown us id 1 data and the same for all id values like 1,2,3. etc. Now we will get the data using id and insert (copy ) into another table. You can get data by id wise. This will help you select an option in your web application. To copy one MySQL table to another table you have to go through the MYSQL syntax.
MYSQL copy one table to another SYNTAX
INSERT INTO table 2 SELECT * FROM table 1 WHERE .
Using the above syntax we will copy one table data to another table. First of all, we will select the data from table 1 and insert into table 2. It will be done by the PHP script.
Now we will create a PHP script for copy one table data to another user id. As you know how to delete data from a table using id. We use the id and delete one by one row. If you want to copy and id to another table. You have to follow delete or update operation. In the delete or update operation, we get the data by id and perform delete and update operation. We will do the same thing here. We will get the data by id and insert into another table. That is a simple process of copy and gettable data by id .
Why need to copy data by id?
If you are working on a PHP project like contest, winner and same like these projects and you want to select one winner. This is done by the id. We create a database table named «winner and we will get the old table data by id and insert (copy) to MySQL winner table. This will help you to select the winner from the registered competitors (or according to your project etc ).
Copy one mysql table data to another mysql table using id
1. First of all create a table table 1 . (like competitors )
2. Now create an another table with same table field (same as competitors table fields )
4. Select data by id . like —>
Select Winner "; //First review the update or delele operation by id
Delete operation
5. We got the data by id and insert (copy) into another MySQL table winner.
Copy one table to another usind id
<?php $databaseHost = 'localhost'; //your db host $databaseName = 'contest'; //your db name $databaseUsername = 'root'; //your db username $databasePassword = '';// db password $mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName); $id = $_GET['id']; $sql="select * from competitors where (id='$id');";// check id is already copied $res=mysqli_query($mysqli,$sql); if (mysqli_num_rows($res) > 0) < // output data of each row $row = mysqli_fetch_assoc($res); if($id==$row['id']) < echo "Already copied"; //error message if already copied >> else < $query=mysqli_query($mysqli,"INSERT INTO winner SELECT * FROM competitors WHERE copy one table to another echo "Successfully copied"; >?>
In the above example, we can copy the data to another table in on click. You can click one button and you will see the id-data copied to another MySQL database.
$query=mysqli_query($mysqli,"INSERT INTO winner SELECT * FROM competitors WHERE copy one table to another
In the part of the PHP code, we have used the MySQL query. We selected the table(competitors) data by id and copy into another table(winner).
You can modify this code according to your need like copy one MySQL table to another MySQL table. Just go through this code.