MySQL - insert into with foreign key index - mysql

Here is the scenario:
I have 2 tables and 2 temporary tables. Before I insert user data to the official tables, I insert them to a temp table to let them do the checks. There is a company table with company info, and a contact table that has contact info. The contact table has a field called company_id which is a foreign key index for the company table.
Temp tables are set up the same way.
I want to do something like: INSERT INTO company () SELECT * FROM temp_company; and INSERT INTO contact () SELECT * FROM temp_contact
My question is, how do I transfer the foreign key from the temp_company to the newly inserted id on the company table using a statement like this? Is there a way to do it?
Currently I am:
grabbing the temp rows
going one by one and inserting them
grabbing the last insert id
then inserting the contacts afterwards with the new last insert id
I just don't know if that is the most efficient way. Thanks!

if you have the same number of columns in both tables and then you should just be able to use the syntax you have there? Just take out the (). Just make sure there aren't any duplicate primary keys:
INSERT INTO company SELECT * FROM temp_company;
INSERT INTO contact SELECT * FROM temp_contact;
You can also specifically specify the columns that get inserted, this way you can specify exactly which column you insert as the new ID.
INSERT INTO company (`ID`,`col_1`,...,`last_col`) SELECT `foreign_key_col`,`col_1`,...,`last_col` FROM temp_company;
INSERT INTO contact (`ID`,`col_1`,...,`last_col`) SELECT `foreign_key_col`,`col_1`,...,`last_col` FROM temp_contact;
Just make sure you are selecting the right # of columns.

Related

insert into 2column table, avoiding duplicate records

I have a table with 2 columns, userid and messageid. I am updating it automatically through a php script, but I can't get a working insert statement. I don't mind if there are duplicates of userid, or duplicates of messageid (in fact there should be duplicates of both), I just don't want any duplicate of the same combination of userid and messageid. Is there any way to write a query that will do this for me, or do I have to handle it at the php level?
I've probably tried 20 different queries that I found on here and google, but have not gotten it right. This was the last thing I tried:
INSERT INTO interests_join (userid, interestid)
VALUES (1, 4)
WHERE NOT EXISTS
(SELECT userid, interestid FROM interests_join WHERE userid = 1 AND interestid = 4)
You can add a UNIQUE KEY, sql will refuse to insert a new row that is a duplicate of an existing one.
ALTER TABLE `interests_join` ADD UNIQUE `row` (`userid`, `interestid`);
Then you'll have to check from PHP if the query was successful or not (error #1062). You can't apply the key if there are duplicate rows, you have to remove them first .

Get all values from table and reuse them to create rows in other table

I have a table (People) with columns (id, name, year). Is there any way I can get all the ids ( SELECT id FROM people ) and use them for creating new rows in other table (people_id, additional_info). I mean that for every id in table People I want to add new row in other table containing the id and some additional information. Maybe something like for-loop is needed here ?
Well, usually you have information on a person and write one record with this information. It makes litte sense to write empty records for all persons. Moreover, when it's just one record per person, why not simply add an information column to the people table?
Anyway, you can create mock records thus:
insert into people_info (people_id, additional_info)
select id, null from people;
Insert into targetTable (id, additional_info)
select id,'additionalinfo' from PEOPLE
No for loop is needed, Just use the above query.
You can use INSERT ... SELECT syntax for MySQL to insert the rows into people_info table (documentation here).
e.g.
insert into people_info(...)
select (...) from people; <and posibly other tables>

My SQL INSERT INTO based on conditions

I have a table called autosaves where i my web-app saves every 4 second a user autosave in case my web-app crashes.
autoSaves
customerId
designType
autosaveFile
The condition is this:
If a customerId and designtype already exists, update the row with these values(customerId designType autosaveFile)
otherwise if the 2 conditions i mentioned do not exist then create a new row with the new values.
I have come accross the Insert Into statement but i cannot seem to understand how to formulate it so that it updates when the 2 conditions are met.
You need to create a unique index on the customerId and designType columns:
CREATE UNIQUE INDEX ix_cust_design ON autoSaves (customerId, designType);
Then you can use the following INSERT statement:
INSERT INTO autoSaves (customerId, designType, autosaveFile)
VALUES (#id, #type, #file)
ON DUPLICATE KEY UPDATE autosaveFile = VALUES(autosaveFile)

Remove Duplicate Data From mysql database

To work on database related stuffs. Mostly it is done when client send you its data in form of excel sheets and you push that data to database tables after some excel manipulations. I have also done it many times.
A very common problem faced in this approach is that it might result in duplicate rows at times, because data sent is mostly from departments like HR and finance where people are not well aware of data normalization techniques [:-)].
I will use Employee table where column names are id, name, department and email.
Below are the SQL scripts for generating the test data.
Create schema TestDB;
CREATE TABLE EMPLOYEE
(
ID INT,
NAME Varchar(100),
DEPARTMENT INT,
EMAIL Varchar(100)
);
INSERT INTO EMPLOYEE VALUES (1,'Anish',101,'anish#howtodoinjava.com');
INSERT INTO EMPLOYEE VALUES (2,'Lokesh',102,'lokesh#howtodoinjava.com');
INSERT INTO EMPLOYEE VALUES (3,'Rakesh',103,'rakesh#howtodoinjava.com');
INSERT INTO EMPLOYEE VALUES (4,'Yogesh',104,'yogesh#howtodoinjava.com');
--These are the duplicate rows
INSERT INTO EMPLOYEE VALUES (5,'Anish',101,'anish#howtodoinjava.com');
INSERT INTO EMPLOYEE VALUES (6,'Lokesh',102,'lokesh#howtodoinjava.com');
Solution:
DELETE e1 FROM EMPLOYEE e1, EMPLOYEE e2 WHERE e1.name = e2.name AND e1.id > e2.id;
delete all duplicate record in excel sheet itself using filter and then insert those record in ur database
use distinct keyword for unique
How to insert Distinct Records from Table A to Table B (both tables have same structure)
check this stack overflow link
Add Unique constraint on name field and use below query
INSERT INTO EMPLOYEE VALUES
Please refer "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
You can always make sure before inserting to the database either that record already exists or not, in your case you can have condition on its unique key which will be different for every employee. Moreover you can have a single column as unique key or a composite key that uses more than one columns to uniquely identify a record.

MySQL: Insert rows using a column from another new table

I've been fighting to get the SQL right on this insert statement.. here's what I'm trying to do:
I have new empty table that has a 1-to-1 relationship with another table. Since all the other columns have default values I only want to insert the primary key column as new rows from the old table. Table names are dealer and dealer_nav and the fields are id and dealer_id respectively.
Thanks!
INSERT INTO dealer_nav(dealer_id) SELECT id FROM dealer (or vice versa, I'm not sure which of 2 tables is new and which is old)