Mysql - move and replace columns - mysql

We have two databases A and B and we want to move and replace some columns with all values from database A to database B
Database.SourceTable >>> move to >>> Database.TargetTable
A.User1 >>> >>> B.User2
The user table has many columns, but we only want to replace some columns: col1, col2 and col3.
How can i do this?
Thank you
EDIT: I forget to say, that i only want to replace the first 100 columns id's.
I mean each column has more than 100 id's and i want to replace first 100; not all.

As you're not able to move datas from a database to another one with a single connection, you can't do it with a single query, you need to do it manually, or with a third party language.
You'll need to :
get one connection per database
get a PRIMARY KEY on your table user
export datas from databaseA
inject these datas to databaseB
Example with PHP/PDO :
// Create 2 connections
try {
$dbA = new PDO('mysql:dbname=databaseA;host=localhost', 'root', '');
$dbB = new PDO('mysql:dbname=databaseB;host=localhost', 'root', '');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
// Get datas from databaseA
$result = $dbA->query("SELECT id, col1, col2, col3 FROM user");
// Prepare REPLACE query for databaseB
$query = "REPLACE INTO user (id, col1, col2, col3) VALUES";
$values = array();
foreach ($result as $row) {
array_push($values, '('.$row['id'].', "'.$row['col1'].'", "'.$row['col2'].'", "'.$row['col3'].'")');
}
$query .= implode(',', $values);
// Execute REPLACE query on databaseB
$stmt = $dbB->prepare($query);
$stmt->execute();

If table1 on db1 database has t1c1, t1c2,t1c3 columns and you want only t1c1, and t1c3 data be copied into table2 of database db2 with columns t2c1 and t2c2 then
insert into db2.table2( t2c1, t2c2 ) select t1c1, t1c3 from db1.table1
should work for you.
And make sure that you have required privileges set to access data from cross database tables or other objects. And you should also check issues with constraints, if any defined, on table2.

Related

Insert all in mysql [duplicate]

Assuming that I have two tables, names and phones,
and I want to insert data from some input to the tables, in one query. How can it be done?
You can't. However, you CAN use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;
http://dev.mysql.com/doc/refman/5.1/en/commit.html
MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)
Old question, but in case someone finds it useful... In Posgresql, MariaDB and probably MySQL 8+ you might achieve the same thing without transactions using WITH statement.
WITH names_inserted AS (
INSERT INTO names ('John Doe') RETURNING *
), phones_inserted AS (
INSERT INTO phones (id_name, phone) (
SELECT names_inserted.id, '123-123-123' as phone
) RETURNING *
) SELECT * FROM names_inserted
LEFT JOIN phones_inserted
ON
phones_inserted.id_name=names_inserted.id
This technique doesn't have much advantages in comparison with transactions in this case, but as an option... or if your system doesn't support transactions for some reason...
P.S. I know this is a Postgresql example, but it looks like MariaDB have complete support of this kind of queries. And in MySQL I suppose you may just use LAST_INSERT_ID() instead of RETURNING * and some minor adjustments.
I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
my way is simple...handle one query at time,
procedural programming
works just perfect
//insert data
$insertQuery = "INSERT INTO drivers (fname, sname) VALUES ('$fname','$sname')";
//save using msqli_query
$save = mysqli_query($conn, $insertQuery);
//check if saved successfully
if (isset($save)){
//save second mysqli_query
$insertQuery2 = "INSERT INTO users (username, email, password) VALUES ('$username', '$email','$password')";
$save2 = mysqli_query($conn, $insertQuery2);
//check if second save is successfully
if (isset($save2)){
//save third mysqli_query
$insertQuery3 = "INSERT INTO vehicles (v_reg, v_make, v_capacity) VALUES('$v_reg','$v_make','$v_capacity')";
$save3 = mysqli_query($conn, $insertQuery3);
//redirect if all insert queries are successful.
header("location:login.php");
}
}else{
echo "Oopsy! An Error Occured.";
}
Multiple SQL statements must be executed with the mysqli_multi_query() function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

How to INSERT an entry without content into a table in ZF2?

In my database there is a table, that contains only one row: id. It's something like a facade for another table:
Now I want to add an entry into whatever_set, in order to be able to create entries in the dependent tables. In SQL I would write:
INSERT INTO whatever_set VALUES ();
But when I try it with Zend\Db
$action = new Insert(whatever_set');
$data = [];
$action->values($data);
$sql = new Sql($this->dbAdapter);
$statement = $sql->prepareStatementForSqlObject($action);
$result = $statement->execute();
I get an exception:
values or select should be present
There are some possible workarounds (see below). But is there though a "Zend way" to save empty with no VALUES? How to do this?
Workaround 1
Custom Insert class.
Workaround 2
Raw SQL like
$sql = 'INSERT INTO whatever_set VALUES ();';
$result = $this->dbAdapter->getDriver()->getConnection()->execute($sql);

Mysql select and insert using prepared statement

My mysql query is working fine
INSERT INTO donor_location (pc_id)
SELECT id
FROM pc
WHERE postcode= ?
i.e gets the postcode id from a postcode table then inserts that id into donor_location table.
I am using mysqli and prepared statements
without the select part it would be quite easy - something like
$stmt = $mysqli->prepare("INSERT INTO donor_charity(
id) values (?)") ;
however I am completely lost about how to incorporate the select
What you do is almost the same, just changing the query bit.
To select all records from charity_donor where the id is 25, you would do the follwing query:
SELECT *
FROM donor_charity
WHERE id = 25
Now to query this, first you have to prepare it:
$stmt = $mysqli->prepare("
SELECT *
FROM donor_charity
WHERE id = ?
");
Now to loop over the results, you must bind the param, and execute the query.
$stmt->bind_param('d', 25 ); // First param means the type of the value you're
passing. In this example, d for digit.
$stmt->execute();
Then you setup an array to hold the data returned from the query,
$row = array();
stmt_bind_assoc($stmt, $row);
And now to loop over the returned data.
while ( $stmt->fetch () ) {
print_r($row); // Should now contain the column.
}
For documentation, see:
Prepare: http://www.php.net/manual/en/mysqli.prepare.php
Bind param: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Execute: http://www.php.net/manual/en/mysqli-stmt.execute.php
Fetch: http://www.php.net/manual/en/mysqli-stmt.fetch.php
You need to use Bind_param after Prepare statement.
$sql = "INSERT INTO donor_charity(
id) values (?)
";
/* create a prepared statement */
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
/* bind parameters for markers */
$stmt->bind_param('ssssss', $id);
$id = '123456';
/* execute query */
$stmt->execute();
Hope this post helps, it's so simple.
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertRecordsUsingPreparedStatement.htm

MYSQL copy row to another identical table with AUTO_INCREMENT id field

I have a movie database where movies are inserted into a table named titles with an AUTO_INCREMENT primary key named titles_id. Users can submit movies anonymously which are inserted into a separate identical table named titles_anon. After reviewing entries in titles_anon I want to insert them into titles but the id column is causing problems
I tried this:
INSERT INTO titles SELECT * FROM titles_anon WHERE
title_id='$title_id';
I either get a duplicate key error, or if the title_id does not already exist in titles it inserts OK but uses the titles_anon id instead of a new AUTO_INCREMENT value which I want.
How do I copy a row between tables when both tables have an AUTO_INCREMENT primary key?
INSERT INTO titles
(column_name1, column_name2, column_name3, column_name4,...)
SELECT title_id, col2, col3, col4,..
FROM titles_anon
WHERE title_id = '$title_id';
You define your fields in SELECT, but omit the PK and add the same fields to INSERT!
You can omit the id column completely, let mysql generate it for you. This need a little longer SQL to specify the exact columns you want to insert.
INSERT INTO titles (columns-other-than-the-primary-key)
SELECT columns-of-the-same-order FROM titles_anon
In PHP you can do something similar to:
$rs = mysql_query("select * from table_orig where RowID=$IDToCopy",$db_conn);
$row = mysql_fetch_assoc($rs);
$sql = '';
$fields = '';
foreach($row as $k => $v){
if($k == "RowID") continue;
$sql .= ",'$v'";
$fields .= ",$k";
}
$sql = "insert into table_copy (".substr($fields,1).") values (".substr($sql,1).")";
mysql_query($sql,$db_conn);
/* copy table with primary key to another table */
$table_old='colaboradores'; // your table old
$table_new='colaboradores2'; //your table new
// sql all columns withou primary key (column_key <> 'pri'
$rs=mysql_query("select column_name from INFORMATION_SCHEMA.COLUMNS
where table_name = '$table_old' and column_key <> 'pri' AND
table_schema = 'your database'");
// get all columns
$rows = mysql_fetch_assoc($rs);
$fields = '';
// mount fields in line
foreach ($rows as $k => $v) {
$fields .= ",$v[0]";
}
// remove first comma
$fields = substr($fields,1);
echo "Sintaxe for Create table in Mysql";
echo "CREATE TABLE $table_new SELECT $fields FROM $table_old ";
echo "Sintaxe for Insert from old table to new table Mysql";
echo "INSERT INTO $table_new $fields SELECT $fields FROM $table_old";

How to append a mysql table to another table in a different database

I would like to grab a table from one database and append this data to a table in another database. However, they have similar numbers (including the id) which need to be updated before they can be copied over. Is there a function available that could do this automatically? Or do I need to write a script in between?
So far I've got:
#!/bin/sh
mysqldump -uuser1 -ppw1 database1 table1 > /home/user/public_html/database1.sql --skip-add-drop-table --skip-create-options
mysql -uuser2 -ppw2 database2 < /home/user/public_html/database1.sql
rm /home/user/public_html/database1.sql
You could select from one table and insert it into another. The results will be "appended" to the original data.
insert into new_table (id, name) select old_id, old_name from old_table;
To append a table from one database to a table from an other database
insert into new_database.new_table (id, name) select old_id, old_name from old_database.old_table;
Sounds like something that would be a lot safer to do via script, which seems simple enough - just grab the data from the first DB and perform batch inserts into the other, letting mysql handle the ids itself. This should take about 10-30 LOC in any descent scripting language, and gives you more control over the outcome.
I solved it by creating a php script that creates new connections for each new database. This script empties the main table first before it will append the data of the other tables. Having the first entry on NULL and having the $row[x] start on 1 makes sure it appends.. Don't know if it's the best solution, but it works.
<?php
$db_user = "database_all_usr";
$db_pw = "";
$db_database = "database_all_db";
mysql_connect("localhost", $db_user, $db_pw) or die(mysql_error());
mysql_select_db($db_database) or die(mysql_error());
$sql = "TRUNCATE TABLE table_all";
mysql_query($sql) or die(mysql_error());
copy_table("database1_db","database1_usr","",$db_database,$db_user,$db_pw);
copy_table("database2_db","database2_usr","",$db_database,$db_user,$db_pw);
function copy_table($db_current,$db_user_current,$db_pw_current,$db_host,$db_user_host,$db_pw_host){
mysql_connect("localhost", $db_user_current, $db_pw_current) or die(mysql_error());
mysql_select_db($db_current) or die(mysql_error());
$sql = "SELECT * FROM table";
$result = mysql_query($sql) or die(mysql_error());
mysql_connect("localhost", $db_user_host, $db_pw_host) or die(mysql_error());
mysql_select_db($db_host) or die(mysql_error());
while ($row = mysql_fetch_row($result)) {
$sql = "INSERT INTO table_all VALUES (NULL, '$row[1]', '$row[2]')"; //adapt to the amount of columns
mysql_query($sql) or die(mysql_error());
}
}
?>