mysql create multiple tables from one table - mysql

I have one table which I have imported into mysql.
Now I need to create multiple related tables.
So basically I have currently got the following
start transaction;
Insert into Address (AddressLine1, AddressLine2, Town, County, Postcode)
Select Distinct Address_line_1, Address_Line_2, Town, County, Postcode from Import;
set addressLastId = last_insert_id();
INSERT INTO Organisation (Name, AddressID)
SELECT DISTINCT Supplier_Name, addressLastId FROM Import;
commit;
The second part where I use the last_insert_id never increments probably because it gets the last insert.
So I need to workout how i can get the previous id for each row inserted into the address table?
Would i need to have an inner loop within the address insert ?
Cheers

I agree with Tim.
After you've populated Address, then you could just run
INSERT INTO Organisation (Name, AddressID)
SELECT DISTINCT Import.Supplier_Name, Address.id
FROM Import INNER JOIN Address ON (set all the address lines and city etc =, since Im guessing there wasnt an address ID in the original import)

You could use a join for the second insert - join Address and Import, and insert the required fields from each into Organisation.
Getting the last insert ID will only work if you process each record sequentially.

Related

Insert records from one table to multiple relational tables using MySQL

I have three tables customers, customer_entity, customer_info. I wanted to insert records from customers table to customer_entity and customer_info at same time, but customer_entity tables primary key will be part of customer_info table.
Assumed Code can we write something like this?
INSERT INTO customer_entity (mobile, name)
INSERT INTO customer_info (customer_entity_id,email, name)
SELECT mobile, name, email customers FROM customers
I dont want to use any programming language only MYSQL
This query may help you.
INSERT INTO customer_entity (mobile,email)
SELECT mobile, email FROM customer ORDER BY id ASC;
INSERT INTO customer_info (customer_entity_id, email)
SELECT customer_entity.id, email, (SELECT email FROM customer WHERE mobile= customer_entity.mobile) FROM customer;
Here the customer table is the main table which has data already and we are inserting it into customer_entity table and customer_info table with customer_entity_id.
You can try using SELECT LAST_INSERT_ID() also:
INSERT INTO customer_entity (mobile,email)
INSERT INTO customer_info (LAST_INSERT_ID(), email)
Docs
If you insert a record into a table that contains an AUTO_INCREMENT
column, you can obtain the value stored into that column by calling
the mysql_insert_id() function.

Insert multiple rows with fields from select [duplicate]

I have a query that inserts using a SELECT statement:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
Is it possible to only select "name, location" for the insert, and set gid to something else in the query?
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.
Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
Of course you can.
One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).
So be careful.
Here is the syntax of the command:
INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;
Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:
SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).
We all know this works.
INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT `col-1`,`col-2`
===========================
Below method can be used in case of multiple "select" statements. Just for information.
INSERT INTO `TableName`(`col-1`,`col-2`)
select 1,2 union all
select 1,2 union all
select 1,2 ;
The right Syntax for your query is:
INSERT INTO courses (name, location, gid)
SELECT (name, location, gid)
FROM courses
WHERE cid = $cid

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.

Insert in a table 2 values

I need some help again.
I have to insert two values in a table into "hospital_database". This table has five columns, and it's called "personas". The columns' names are "cod_hospital(PK)", "DNI", "Apellidos", "Funcion" and "Salario"... I have to insert "99887766" and "Martínez Martínez, Alejandro" into "DNI" and "Apellidos", but according to the question, I must to insert into a "hospital" where only there's 1 person...
I have to use "insert+select" and my last effort was this:
insert into personas
values (99887766, 'Martínez Martínez, Alejandro');
select dni, apellidos
from personas
where count(dni)=1;
I tried something like that, and a lot of ways... but It doesn't work like the question asks. I have to use insert+select, so I shouldn't write ";" before "select".
Honestly I'm still guessing at this a little, but maybe you intend to insert an additional row in the personas table if only 1 row exists in that table for a given hospital code. To do this you need to use group by with having:
insert into personas (cod_hospital, dni, apellidos)
select cod_hospital, 99887766, 'Martínez Martínez, Alejandro'
from personas
group by cod_hospital
having count(*)=1
insert have several sintaxis and looks like you are mixing all of them
One is insert values http://www.w3schools.com/sql/sql_insert.asp
INSERT INTO table_name
VALUES (value1,value2,value3,...);
the other insert from a select
http://www.w3schools.com/sql/sql_insert_into_select.asp
INSERT INTO table2
SELECT * FROM table1;
And if you dont include all the field, you have to indicate which fields are you inserting
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
cod_hospital is the table's PK, you could only insert one person per hospital, change your PK to: cod_hospital, dni

Can one get all of the identities of a block insert of records?

Considering the following TSQL:
INSERT INTO Address(Street1, City, State, ZipCode)
SELECT Street1, City, StateCode, ZipCode
FROM Contact
The Address has an identity column that is automatically set. Is there a way to get a list of the identities of Address records newly inserted?
I know there is ##IDENTITY, but that just returns the last identity.
Assuming the identity column is called AddressID, you can:
INSERT INTO dbo.Address(Street1, ...)
OUTPUT inserted.AddressID
SELECT Street1, ...
FROM dbo.Contact;
Or:
DECLARE #NewAddresses TABLE(AddressID INT);
INSERT INTO dbo.Address(Street1, ...)
OUTPUT inserted.AddressID INTO #NewAddresses
SELECT Street1, ...
FROM dbo.Contact;
Keep in mind ##IDENTITY should almost never be used. Even when dealing with single-row inserts, SCOPE_IDENTITY() is much safer. See this answer for more background.