MySQL Insert Into from one Database in another - mysql

I need to migrate data from one Database to another one, both are on the same local system.
The tables and columns got different names and I mustn't migrate all the Columns from the old Database, so
Select * doesn't work for me.
INSERT INTO newDatabase.table1(Column1, Column2);
SELECT oldDatabase.table1(column1, column2) FROM oldDatabase.table1
but all i got is a #1064 - Syntax Error
What is the error in my Query and How can i fix this ?
Thanks in advance

Your query should go like this:
INSERT INTO newDatabase.table1 (Column1, Column2)
SELECT column1, column2 FROM oldDatabase.table1;
UPDATE
Since this answer is getting more attention than I even anticipated, I should expand on this answer. First of all, it might not be obvious from the answer itself, but the columns do not need to have the same name. So, following will work too (assuming that the columns exist in their respective tables):
INSERT INTO newDatabase.table1 (Column1, Column2)
SELECT SomeOtherColumn, MoreColumns FROM oldDatabase.table1;
Furthermore, they don't even need to be real columns in the table. One of the examples for transforming data that I use quite often is:
INSERT INTO newDatabase.users (name, city, email, username, added_by)
SELECT CONCAT(first_name, ' ', last_name), 'Asgard', CONCAT(first_name,'#gmail.com'), CONCAT(first_name,last_name), 'Damir' FROM oldDatabase.old_users;
So, as it might be more obvious now, the rule is, as long as the SELECT query returns same number of columns that INSERT query needs, it can be used in place of VALUES.

INSERT INTO db1.table SELECT * FROM db2.table;
If you want to copy data to same tables of different db.

You said "The tables and columns got different names", but you still used the same names. Try this:
INSERT INTO newDatabase.newtable1 (newColumn1, newColumn2)
SELECT oldcolumn1, oldcolumn2 FROM oldDatabase.oldtable1;

CREATE TABLE db2.table LIKE db1.table;
INSERT INTO db2.table
SELECT column_name FROM db1.table

Related

ERROR 1093 (HY000): Nested select on insert [duplicate]

Clearly the following is incorrect.
INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),'name');
I get the value:
SQL query:
INSERT INTO `aTable` (`A`, `B` )
VALUES
(
(
SELECT MAX(`A`)
FROM `aTable`
) *2
, 'name'
)
MySQL said:
1093 - You can't specify target table 'aTable' for update in FROM clause
So, I'm trying to make a bitmap table, each row corresponds to one Bit, and has a 'map' value.
To insert in the table, I don't want to do two queries, I want to do one.
How should I do this?
No one commented on this, but since I am trying to make a bitmap, it should be * 2 not ^ 2, my mistake, please note that is why the comments often say ^ 2, it was an error in the version that the commenters read.
try:
insert into aTable select max(a)^2, 'name' from aTable;
or
insert into aTable select max(a)^2, 'name' from aTable group by B;
If you need a join, you can do this:
insert into aTable select max(a)^2, 'name' from aTable, bTable;
My "Server version" is "5.0.51b-community-nt MySQL Community Edition (GPL)"
Actually, you can alias the table on the insert. I've seen this question all over the place, but no one seems to have tried that. Use a subquery to get the max from the table, but alias the table in the subquery.
INSERT INTO tableA SET fieldA = (SELECT max(x.fieldA) FROM tableA x)+1;
A more complex example, where you have a corresponding secondary key and might be inserting the FIRST record for the corresponding secondary key:
INSERT INTO tableA SET secondaryKey = 123, fieldA = COALESCE((SELECT max(x.fieldA) FROM tableA x WHERE x.secondaryKey = 123)+1,1);
By aliasing the table, it doesn't throw the error and seems to work. I just did this while coding something, although I can't see if there area any silly syntax errors above, I would try that type of syntax.
I take it that INSERT ... SELECT isn't working? I see this in the documentation for it:
The target table of the INSERT
statement may appear in the FROM
clause of the SELECT part of the
query. (This was not possible in some
older versions of MySQL.) In this
case, MySQL creates a temporary table
to hold the rows from the SELECT and
then inserts those rows into the
target table.
Out of curiosity, which version of MySQL are you using?
I think you need to drop the "VALUES", and have a valid select statement.
see this link
I'm not particularly a mySQL guy, I use MSSQL mostly. But If you format the select statement correctly, It should work.
as soon as the Select is correct you can do this.

How to copy MySQL tables of database to another database in the same server? [duplicate]

I need to migrate data from one Database to another one, both are on the same local system.
The tables and columns got different names and I mustn't migrate all the Columns from the old Database, so
Select * doesn't work for me.
INSERT INTO newDatabase.table1(Column1, Column2);
SELECT oldDatabase.table1(column1, column2) FROM oldDatabase.table1
but all i got is a #1064 - Syntax Error
What is the error in my Query and How can i fix this ?
Thanks in advance
Your query should go like this:
INSERT INTO newDatabase.table1 (Column1, Column2)
SELECT column1, column2 FROM oldDatabase.table1;
UPDATE
Since this answer is getting more attention than I even anticipated, I should expand on this answer. First of all, it might not be obvious from the answer itself, but the columns do not need to have the same name. So, following will work too (assuming that the columns exist in their respective tables):
INSERT INTO newDatabase.table1 (Column1, Column2)
SELECT SomeOtherColumn, MoreColumns FROM oldDatabase.table1;
Furthermore, they don't even need to be real columns in the table. One of the examples for transforming data that I use quite often is:
INSERT INTO newDatabase.users (name, city, email, username, added_by)
SELECT CONCAT(first_name, ' ', last_name), 'Asgard', CONCAT(first_name,'#gmail.com'), CONCAT(first_name,last_name), 'Damir' FROM oldDatabase.old_users;
So, as it might be more obvious now, the rule is, as long as the SELECT query returns same number of columns that INSERT query needs, it can be used in place of VALUES.
INSERT INTO db1.table SELECT * FROM db2.table;
If you want to copy data to same tables of different db.
You said "The tables and columns got different names", but you still used the same names. Try this:
INSERT INTO newDatabase.newtable1 (newColumn1, newColumn2)
SELECT oldcolumn1, oldcolumn2 FROM oldDatabase.oldtable1;
CREATE TABLE db2.table LIKE db1.table;
INSERT INTO db2.table
SELECT column_name FROM db1.table

SQL Query to INSERT multiple rows with SELECT

I need to read data from one table and insert into multiple rows in another table in a MySQL database.
Table 1 looks like:
ID, name, e-mail, phone, city, ..., ....
In Table 2 I need to insert data like:
(row1) ID, "name", name
(row2) ID, "e-mail, e-mail
(row3) ID, "phone", phone
...
...
Table 1 has about 3000 rows
I guess I need to use some kind of foreach or do..while but can't find anything that works.
Can anyone give me a clue how to do this?
If I understand your question correctly, you are wanting to do a query on table1 that returns multiple rows, and then insert those into table2 in a single loop. That's the INSERT INTO SELECT statement:
INSERT INTO table2
(name, email, phone)
SELECT name, email, phone
FROM table1;
It can be modified to grab specific results as well:
INSERT INTO table2
(name, email, phone)
SELECT name, email, phone
FROM table1
WHERE name = 'target person';
More information can be found at http://dev.mysql.com/doc/refman/5.7/en/insert-select.html and http://www.w3schools.com/sql/sql_insert_into_select.asp.
EDIT:
Based on your comment, it sounds like you're trying to do this:
SQL split values to multiple rows.
I can't think of a situation where you'd actually want to do that, as you can access all of the data in your existing table as is, and it seems to be bad practice to split data in the way you're requesting. However, the solutions in the above thread should be applicable to what you're trying to do.
Ultimately, you may want to look at how you're actually retrieving the data. Modifying that code would be a better idea :)
Just do a simple INSERT INTO SELECT with group by "id". Here for each id it will insert a new record.
INSERT INTO table2 (name, email, phone)
SELECT name, email, phone FROM table1 GROUP BY id;
Just an update on how I did do this. Since I don't have full access to the database server, I can just add/remove data and create new tables, it was not possible to create a function as suggested in the link provided in the answer.
Instead of trying to loop through the data I did an INSERT for each new row like:
INSERT INTO table2 (id,col2,col3)
SELECT id,'name',name FROM table1;
INSERT INTO table2 (id,col2,col3)
SELECT id,'email',email FROM table1;
Thanks again for the help provided.

Database INSERT INTO SET ... WHERE(SELECT ...)

I am trying to insert my values into table if Admin_User_Role_Id value against Admin_Id is not present in the table. Is it possible to insert!
My Table Structure:
Admin_User_Id (FK)
Admin_User_Role_Id (FK)
Is_Enabled (boolean flag)
Query which I tried, but not success
INSERT INTO role_association
SET Admin_User_Id=61, Admin_User_Role_Id=2, Is_Enabled=0
WHERE Admin_User_Role_Id
NOT IN
(SELECT Admin_User_Id, Admin_User_Role_Id FROM role_association)
I think it is possible but my logic is wrong. How should I manage this query to work successfully!
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
Probably you take care about where condition in your programming logic and write a simple insert statement and the depending on your logic use this statement to insert the records. Hope you got my point.
You want to insert your values in your table using this query for your reference
INSERT INTO Yourtablename(column1,column2,column3,...)
VALUES ('value1','value2','value3',.....);
You want to ADD one new column in your table means using this query
** ALTER TABLE table_name ADD column_name datatype**

Duplicate all data in the same table MYSQL

I'm looking for a way I can duplicate all the rows in my database, I tried exporting it and then importing but I get the duplicate key error.
The reason is purely for testing purposes, I just want a load of dummy data in there to test the system I have out.
Is there a direct statement for this? Or is there a way to export all data except ID (or change ID to MAX(ID) + 1 or AUTO INCREMENT)?
You can try this:
INSERT INTO your_table_name(parent_id,priority,text,shortname,weighting,g_or_a,
dept,ksf,day_start,day_end,date_start,date_end,depends_on,is_question,budget,
ccode,responsible,accountable,consulted,informed)
(SELECT parent_id,priority,text,shortname,weighting,g_or_a,dept,ksf,
day_start,day_end,date_start,date_end,depends_on,is_question,budget,ccode,
responsible,accountable,consulted,informed FROM your_table_name);
Firstly, insert one row in the table 'your_table_name'. Replace your_table_name with the actual table name in above code & execute the code repeatedly until it satisfies the required row numbers. I think it should work.
Put 1 record and then run:
insert into mytable select * from mytable
10 times. This will give you 1024 records. Continue until satisfied.
You could use an INSERT and the values would be a SELECT, just don't select the primary key and don't define it in the insert fields.
Imagine a table with 3 fields, the_pk, field_1, field_2
Something like
INSERT INTO the_table(field_1, field_2) (SELECT field_1, field_2 FROM the_table)