avoid Duplicate entry in mysql - php

I have two tables say, Table1 and Table2.
Table1 contain 20 fileds with primary key ID for Table1 auto increment and Table2 contain same 20 column with primary key ID1 for TAble2 auto increment.
Table1- ID,Column1,Column2,Column3....,Colunm20.
Table2-ID1,ID,Column1,Column2,.....,Column20
I insert each record into Table1. I want to check duplicate Entry for Table1 if all field are same.
Table2 contain the Entry form Table1.If I modified record First record goes to Table2 as it is then it will update into Table1.(i.e first copy the record into Table2 for backup and then update into Table1) So, same condition for Duplicate entry check near Table2 also need. Please Help!
I have coded this in php.

You can write trigger for table 1 which is copying data from table2 on every insert event.
And for unique data either you can check it on php side before you insert or you can define column as unique. Your question is bit confusing so Its difficult to give exact answer.
What are the unique columns ??

Related

insert data from old table to new table

I have two database table.Two table have same structure. Now i want to insert data from old table to new table if data already exists it will update the old data otherwise insert new. I want to insert or update data by matching some column field value. Any help?
You can make use of ON DUPLICATE KEY UPDATE feature of MySQL. From MySQL doc -
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL
performs an UPDATE of the old row.
So, if you have keys defined in the tables you can use this feature. For example, your statement will look like -
insert into target_table (col1, col2, ...)
select col1, col2,... from source_table
on duplicate key update
col1 = values(col1),
col2 = values(col2),
The Best way is you can use the left outer join concept.That will be easy.
INSERT INTO table1
(col_1, col_2, col_3, col_4, col_5) values("","","","")
SELECT
table2_col_1,
table2_col_2,
table2_col_3,
table2_col_4,
1
FROM
table_2 AS t2
LEFT OUTER JOIN
table1 AS t1
ON
t1.col_1 = t2.table2_col_1;
UPDATE table_2
SET table2_col_1 = 'value'// here is the value that you need to implement
WHERE t1.col_1=t2.table2_col_1;//here is your condition
From your Question , i understood that your table2 is not that much important.
So you can drop the values present in the entire table2 ,so that the structure will not get affected.After that was finished.. you can just export the insert query to implement the values that is present in the table1.

insert into mysql if not exist else update [duplicate]

UPDATE AggregatedData SET datenum="734152.979166667",
Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667";
It works if the datenum exists, but I want to insert this data as a new row if the datenum does not exist.
UPDATE
the datenum is unique but that's not the primary key
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
Try using this:
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...
The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...
This is not too bad, but we could actually combine everything into one query. I found different solutions on the internet. The simplest, but MySQL only solution is this:
INSERT INTO wp_postmeta (post_id, meta_key)
SELECT
?id,
‘page_title’
FROM
DUAL
WHERE
NOT EXISTS (
SELECT
meta_id
FROM
wp_postmeta
WHERE
post_id = ?id
AND meta_key = ‘page_title’
);
UPDATE
wp_postmeta
SET
meta_value = ?page_title
WHERE
post_id = ?id
AND meta_key = ‘page_title’;
Link to documentation.
I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:
replace into last_recogs (id, hasher_id, hash_id, last_recog)
select l.* from
(select id, hasher_id, hash_id, [new_value] from last_recogs
where hasher_id in (select id from hashers where name=[hasher_name])
and hash_id in (select id from hashes where name=[hash_name])
union
select 0, m.id, h.id, [new_value]
from hashers m cross join hashes h
where m.name=[hasher_name]
and h.name=[hash_name]) l
limit 1;
This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

Copying tables mysql

I am newbie to sql advance and i am trying to insert rows to one table by selecting from another one. But some bug is coming out.
Here is my problem
So i have two tables
table1 having id(autoincrement), names
table2 having id(autoincrement), names
Now at starting table1 is empty and table2 having 2 rows
1,'myself'
2,'yourself'
So the problem starts here
When i execute following query
Insert into table1 (names) select (names) from table2
So now both rows of table2 must be copied to table1
Ya its working fine.
But what about autoincrement value of id?
By till now table1 autoincrement id should store 3 since next row to be inserted should have id 3
But its not working like expected so table1 autoincrement id stores 4 i.e, 1(current id value)+2*(no of rows inserted)-1
So next time when i execute same query it inserts row with id 4. Skips id=3.
This is problem hope you all got what i am talking about.
Thanks for helping in advance.
Try this
INSERT INTO TABLE1 SELECT * FROM TABLE2
Go ahead an copy your data over, and then you can modify the starting auto_inc to whatever you choose.
ALTER TABLE table AUTO_INCREMENT = 1000;
Alter Table will take around 1 sec as it first creates shadow of the table then the query is processed and if the no. of rows of table goes above then it may take around 20-30 sec. so I dont think that alter is good answer for this problem. Hope someone will help you with insert command such as:
Insert into table1 set id = 1; etc...

How to insert a id of a new row into another linking table?

I've a table with the purpose of linking two other tables with foreign keys (table 3).
table1 = id, name
table2 = id, sport
table3 = fk_table1_id, dk_table2_id
I do server side code with php and i need a way to automatic insert a row into table 3 when a row is inserted into table2.
But i dont know how to do a php query that will get the generated id of the new row in table2?(The id of table one i do have stored in a php variable)Im a looking at a smart stored procedure?
Steps to follow:
Insert a row into table2.
Find the generated key from table2 and assign it to a PHP variable.
-- read this into a php variable, say, $last_key
SELECT LAST_INSERT_ID();
Use the $last_key in insert statement for table3.
You can Follow below Steps:
1) Make ID to AUTO_INCREMENT IN Table2
2) Create Store Procedure that work as below:
A) INSERT Value to your Table2 :
B) Increase ID value : SELECT LAST_INSERT_ID() INTO VARIABLE;
C) Insert Value to your Table3 : use VARIABLE to get ID of Table2

reference auto-increment columns?

I have 2 tables that I am working with that use the same column; one table contains the text and the other table contains the images; they use the column listing_id so that the right text shows up with the right images;
my problem is that because column listing_id is auto-increment, my first table is able to have an insert into query that is able to insert the text and then +1 the column listing_id; however the 2nd table I use another INSERT INTO query will not have the right listing_id,
because some entries for listing_id have been deleted, meaning that the 2nd table's listing_id will always be behind the 1st tables listing_id;
how do I reference the column listing_id?
You need to create an INT column called something like "parent_id" in the dependant tables that stores the id of the main table that it is referencing. When you select records from the first, you would then JOIN the tables with the auto_increment field of the first field against the "parent_id" of the second.
As MrSlayer mentions, use the newly inserted ID of the first table to update "parent_id". You should typically have a unique ID field in the second table for uniqueness, but it shouldn't be part of the relationship to the first table.
If you're unclear about how to get the id that the first table auto_increments to when you insert, use mysql_insert_id().
mysql_query("INSERT INTO table1 ...");
echo "Last inserted record_id in table1 was " . mysql_insert_id();
INSERT INTO table1 (mytextcolumn) VALUES('text');
INSERT INTO table2 (parent_id,image_name) VALUES(LAST_INSERT_ID(),'someimage.png');

Categories