MySQL의 기존 행에 대한 Insert Statement 가져 오기
MySQL을 사용하여 쿼리를 실행할 수 있습니다.
SHOW CREATE TABLE MyTable;
그리고 특정 테이블에 대한 테이블 작성 명령문을 리턴합니다. 테이블이 이미 작성되어 있고 다른 데이터베이스에서 동일한 테이블을 작성하려는 경우 유용합니다.
이미 존재하는 행 또는 행 집합에 대해 insert 문을 가져올 수 있습니까? 일부 테이블에는 많은 열이 있으므로 insert 문을 쓰거나 데이터를 CSV로 내 보낸 다음 동일한 데이터를 가져 오지 않고 다른 데이터베이스로 행을 전송하기 위해 insert 문을 가져올 수 있으면 좋을 것입니다. 다른 데이터베이스로.
명확히하기 위해, 내가 원하는 것은 다음과 같이 작동하는 것입니다.
SHOW INSERT Select * FROM MyTable WHERE ID = 10;
그리고 나를 위해 다음을 반환하십시오.
INSERT INTO MyTable(ID,Col1,Col2,Col3) VALUES (10,'hello world','some value','2010-10-20');
INSERT
MySQL 콘솔에서 문장 을 얻는 방법은 없지만 Rob이 제안한 것처럼 mysqldump를 사용하여 문장 을 얻을 수 있습니다 . -t
테이블 작성을 생략하도록 지정 하십시오.
mysqldump -t -u MyUserName -pMyPassword MyDatabase MyTable --where="ID = 10"
MySQL Workbench에서는 단일 테이블 쿼리의 결과를 INSERT
명령문 목록으로 내보낼 수 있습니다 . 쿼리를 실행 한 후 다음을 수행하십시오.
Export/Import
결과 위 의 플로피 디스크를 클릭하십시오- 대상 파일에 이름을 지정하십시오
- 창 하단에서
Format
선택SQL INSERT statements
- 딸깍 하는 소리
Save
- 딸깍 하는 소리
Export
SHOW CREATE TABLE MyTable 에서 생성 한 SQL로 테이블을 복사 했으므로 다음을 수행하여 데이터를 새 테이블로로드 할 수 있습니다.
INSERT INTO dest_db.dest_table SELECT * FROM source_db.source_table;
INSERT 문을 정말로 원한다면 내가 아는 유일한 방법은 mysqldump http://dev.mysql.com/doc/refman/5.1/en/mysqldump.htm 을 사용하는 것 입니다. 특정 테이블의 데이터를 덤프하고 행을 제한하는 옵션을 제공 할 수 있습니다.
나는 이것을 할 PHP 함수를 작성했다. 히스토리 테이블을 삭제 한 후 레코드를 교체해야 할 경우를 대비하여 insert 문을 작성해야했습니다.
function makeRecoverySQL($table, $id)
{
// get the record
$selectSQL = "SELECT * FROM `" . $table . "` WHERE `id` = " . $id . ';';
$result = mysql_query($selectSQL, $YourDbHandle);
$row = mysql_fetch_assoc($result);
$insertSQL = "INSERT INTO `" . $table . "` SET ";
foreach ($row as $field => $value) {
$insertSQL .= " `" . $field . "` = '" . $value . "', ";
}
$insertSQL = trim($insertSQL, ", ");
return $insertSQL;
}
Laptop Lift의 코드는 정상적으로 작동하지만 사람들이 좋아할만한 몇 가지 사항이 있습니다.
데이터베이스 핸들러는 하드 코딩되지 않은 인수입니다. 새로운 mysql API를 사용했습니다. 유연성을 위해 $ id를 선택적 $ where 인수로 대체했습니다. 누군가가 SQL 주입을 시도하고 따옴표와 관련된 간단한 파손을 피하려고 시도한 경우 real_escape_string을 사용했습니다. INSERT table (field...) VALUES (value...)...
필드를 한 번만 정의한 다음 각 행의 값을 나열하기 위해 구문을 사용했습니다 (임플란트는 훌륭합니다). Nigel Johnson이 지적 했으므로 NULL
처리를 추가했습니다 .
나는 $array[$key]
그것이 어떻게 든 변할 까봐 걱정했기 때문에 사용 했지만, 뭔가 잘못되지 않으면 어쨌든 안됩니다.
<?php
function show_inserts($mysqli,$table, $where=null) {
$sql="SELECT * FROM `{$table}`".(is_null($where) ? "" : " WHERE ".$where).";";
$result=$mysqli->query($sql);
$fields=array();
foreach ($result->fetch_fields() as $key=>$value) {
$fields[$key]="`{$value->name}`";
}
$values=array();
while ($row=$result->fetch_row()) {
$temp=array();
foreach ($row as $key=>$value) {
$temp[$key]=($value===null ? 'NULL' : "'".$mysqli->real_escape_string($value)."'");
}
$values[]="(".implode(",",$temp).")";
}
$num=$result->num_rows;
return "INSERT `{$table}` (".implode(",",$fields).") VALUES \n".implode(",\n",$values).";";
}
?>
선택 쿼리를 만들고 결과를 가리키고 sql로 내보내기를 선택할 수있는 SQLYOG 프로그램을 사용합니다 . 이것은 삽입 문을 제공합니다.
MySQL 작업대 내에서 다음을 수행하십시오.
Click Server > Data Export
In the Object Selection Tab select the desired schema.
Next, select the desired tables using the list box to the right of the schema.
Select a file location to export the script.
Click Finish.
Navigate to the newly created file and copy the insert statements.
If you want get "insert statement" for your table you can try the following code.
SELECT
CONCAT(
GROUP_CONCAT(
CONCAT(
'INSERT INTO `your_table` (`field_1`, `field_2`, `...`, `field_n`) VALUES ("',
`field_1`,
'", "',
`field_2`,
'", "',
`...`,
'", "',
`field_n`,
'")'
) SEPARATOR ';\n'
), ';'
) as `QUERY`
FROM `your_table`;
As a result, you will have insers statement:
INSERT INTO your_table
(field_1
, field_2
, ...
, field_n
) VALUES (value_11, value_12, ... , value_1n);
INSERT INTO your_table
(field_1
, field_2
, ...
, field_n
) VALUES (value_21, value_22, ... , value_2n);
/...................................................../
INSERT INTO your_table
(field_1
, field_2
, ...
, field_n
) VALUES (value_m1, value_m2, ... , value_mn);
, where m - number of records in your_table
you can use Sequel pro to do this, there is an option to 'get as insert statement' for the results obtained
With PDO you can do it this way.
$stmt = DB::getDB()->query("SELECT * FROM sometable", array());
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$fields = array_keys($array[0]);
$statement = "INSERT INTO user_profiles_copy (".implode(",",$fields).") VALUES ";
$statement_values = null;
foreach ($array as $key => $post) {
if(isset($statement_values)) {
$statement_values .= ", \n";
}
$values = array_values($post);
foreach($values as $index => $value) {
$quoted = str_replace("'","\'",str_replace('"','\"', $value));
$values[$index] = (!isset($value) ? 'NULL' : "'" . $quoted."'") ;
}
$statement_values .= "(".implode(',',$values).")";
}
$statement .= $statement_values . ";";
echo $statement;
You can create a SP with the code below - it supports NULLS as well.
select 'my_table_name' into @tableName;
/*find column names*/
select GROUP_CONCAT(column_name SEPARATOR ', ') from information_schema.COLUMNS
where table_schema =DATABASE()
and table_name = @tableName
group by table_name
into @columns
;
/*wrap with IFNULL*/
select replace(@columns,',',',IFNULL(') into @selectColumns;
select replace(@selectColumns,',IFNULL(',',\'~NULL~\'),IFNULL(') into @selectColumns;
select concat('IFNULL(',@selectColumns,',\'~NULL~\')') into @selectColumns;
/*RETRIEVE COLUMN DATA FIELDS BY PK*/
SELECT
CONCAT(
'SELECT CONCAT_WS(','''\'\',\'\''',' ,
@selectColumns,
') AS all_columns FROM ',@tableName, ' where id = 5 into @values;'
)
INTO @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
/*Create Insert Statement*/
select CONCAT('insert into ',@tableName,' (' , @columns ,') values (\'',@values,'\')') into @prepared;
/*UNWRAP NULLS*/
select replace(@prepared,'\'~NULL~\'','NULL') as statement;
For HeidiSQL users:
If you use HeidiSQL, you can select the row(s) you wish to get insert statement. Then right click > Export grid rows > select "Copy to clipboard" for "Output target", "Selection" for "Row Selection" so you don't export other rows, "SQL INSERTs" for "Output format" > Click OK.
The insert statement will be inside you clipboard.
I think that the answer provided by Laptop Lifts is best...but since nobody suggested the approach that I use, i figured i should chime in. I use phpMyAdmin to set up and manage my databases most of the time. In it, you can simply put checkmarks next to the rows you want, and at the bottom click "Export" and chose SQL. It will give you INSERT statements for whichever records you selected. Hope this helps.
Based on your comments, your goal is to migrate database changes from a development environment to a production environment.
The best way to do this is to keep your database changes in your source code and consequently track them in your source control system such as git or svn.
you can get up and running quickly with something like this: https://github.com/davejkiger/mysql-php-migrations
PHP의 매우 기본적인 사용자 지정 솔루션으로 다음과 같은 기능을 사용할 수 있습니다.
function store_once($table, $unique_fields, $other_fields=array()) {
$where = "";
$values = array();
foreach ($unique_fields as $k => $v) {
if (!empty($where)) $where .= " && ";
$where .= "$k=?";
$values[] = $v;
}
$records = query("SELECT * FROM $table WHERE $where", $values);
if (false == $records) {
store($table, array_merge($unique_fields, $other_fields));
}
}
그런 다음 환경을 사양에 맞게 업데이트하는 마이그레이션 스크립트를 만들 수 있습니다.
참고 URL : https://stackoverflow.com/questions/3978326/get-insert-statement-for-existing-row-in-mysql
'programing tip' 카테고리의 다른 글
네이티브 fetch () 네트워크 요청 실패 (0) | 2020.07.15 |
---|---|
Oracle SELECT TOP 10 레코드 (0) | 2020.07.15 |
특정 커밋 이후 커밋을 나열하는 방법은 무엇입니까? (0) | 2020.07.15 |
Label과 TextBlock의 차이점 (0) | 2020.07.15 |
Windows 서비스로 node.js를 설치하는 방법? (0) | 2020.07.15 |