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.
Related
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
I want to insert data from a table WorkTableA to another table TableA, without duplicating the data (i.e. do not insert into WorkTableA if the customer name already exists).
Is there a way of doing it through VBA code.
The field name and their properties in both tables are identical.
What you need is an INSERT INTO statement
INSERT INTO WorkTableA
( CustomerName, Col2, Col3...)
SELECT CustomerName, Col2, Col3
FROM TableA LEFT JOIN WaorkTableA ON TableA.CustomerName = WORKTABLEA.CustomerName
WHERE WorkTableA.CustomerName IS NULL
Something like this might work.
The SELECT part of the statement will select only the ones that DO NOT EXIST in WorkTableA
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
I understand how to do an insert into when all the input data is known, and I know how to do an insert into when all the data is dependent on a select, but I can't find how to do the in between. Where I'm at now:
INSERT INTO takes (stu_id, "CS-001", 1, "Autumn", 2009, null)
VALUES (SELECT id AS stu_id
FROM student
WHERE dept_name = "Comp. Sci.")
Thus I know all the other input data except the student's id, however MySQL just gives me a syntax error.
INSERT INTO takes (stu_id, col2, col3, col4, col5, col6)
SELECT id, 'CS-001', 1, 'Autumn', 2009, null
FROM student
WHERE dept_name = 'Comp. Sci.'
I don't know your destination column names - you have to replace them with the real ones in the query above.
Insert queries can be structured like this:
insert into table
(field1, field2, etc)
(value1, value2 etc)
or like this:
insert into table
(field1, field2, etc)
select this, that, etc
from etc
You tried to combine the two. That's one of the reasons you got an error.
juergen's answer is an example of the 2nd construct. His this and that is a combination of fields and constant values. That's perfectly ok. If you are getting syntax errors, it's in your details. His answer shows the right general idea.
It's often worthwhile to build your query step by step. Start with this:
insert into takes
(stu_id)
select id
from student
where dept_name = 'Comp. Sci'
If that works, add one field inside the brackets and whatever is appropriate to the select clause of your query. Keep going with these baby steps until you get it right. It's an approach I often take.
I have a mysql query doubt.
I have a student table email is the column name, before inserting new student i need to make sure same email can't be inserted.How can i right insert and check in one query(using sub query).
Please help me to find a solution
Thanks
The right way is to enforce it with unique constraint, but if you want to do in insert query, you can try something like
insert into student(field1, field2, email)
select 'value1', 'value2','test#test.com' from dual
where not exists (select null from student where email='test#test.com')
Note :if you use an engine that supports transactions, you may still end up having duplicate)