I am trying to use following code segment to update the database when inserting duplicates. But instead of updating it still inserting duplicate rows. Why?
$import = "INSERT INTO data(Product,Courier,Received_Date,Acc_No,Received_By,Delivered_Date,Month,Year,Bill_Run,Dispatch_Type,Status,Bounce_Code) values('$data[0]','$data[1]','$Received_Date','$data[3]','$data[4]','$Delivered_Date','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]') ON DUPLICATE KEY UPDATE Acc_No = '$data[3]'
For 'ON DUPLICATE KEY UPDATE' to work you need a unique or primary key constraint on a table. Only if you would get a key conflict on inserting the 'ON DUPLICATE KEY UPDATE ' code is executed.
Add primary key constraint on the table:
ALTER TABLE table_name add primary key(col_name)
add Unique Key in column name table
enter link description here
enter link description here
enter link description here
Related
I want to add complex unique key to existing table. Key contains from 4 fields (user_id, game_id, date, time).
But table have non unique rows.
I understand that I can remove all duplicate dates and after that add complex key.
Maybe exist another solution without searching all duplicate data. (like add unique ignore etc).
UPD
I searched, how can remove duplicate mysql rows - i think it's good solution.
Remove duplicates using only a MySQL query?
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
Set Multiple Unique key into table
ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);
I am providing my solution with the assumption on your business logic. Basically in my design I will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
If yourColumnName has some values doesn't unique, and now you wanna add an unique index for it. Try this:
CREATE UNIQUE INDEX [IDX_Name] ON yourTableName (yourColumnName) WHERE [id]>1963 --1963 is max(id)-1
Now, try to insert some values are exists for test.
I try to use on duplicate key update in my query but it still duplicate some value.
My query is like this:
$insert=mysqli_query($conn,"insert into tbl_staffdistribution(db_user,db_name,db_responsible,db_date)values('$user','$name','$responsible','$formatteddatetimein') on duplicate key update db_user='$user',db_name='$name',db_responsible='$responsible',db_date='$formatteddatetimein'")or die(mysqli_error($conn));
I have db_id in my database is a primary key auto increment.
The problem is that I have a duplicate value in my database and that should not happen How can I solve this problem ??
In order to do this. you should be having a unique key within your table so that you can use it for on duplicate key update as such. The unique key can be your primary or some other field from your table. You can do something like this within your query:
ON DUPLICATE KEY UPDATE someID = VALUES(someID)
A clear cut explanation from MySQL.
Duplicate entry '20' for key 'user_id'
$userid = its foreign key (20)
$query = mysql_query("insert into qualification (q_id,course_name,institute_name,pass_year,user_id) values ('','$coursename','$institutename','$passyear','$userid')") or die(mysql_error());
Does anybody have an idea on how to skip this error and add multiple record on the same userid ?
When you get this error, you have a UNIQUE or PRIMARY key constraint for user_id in your database. As Marc B already said. Remove the unique constraint from the user_id.
You asked Marc:
Why remove unique constraint?
Simply because then you can't have two records with the same user_id in your table. Then you also can't use it as a key for table. You can still use an index on user_id to speed up queries for this field.
I have a mysql on duplicate key statement.
mysql_query("INSERT INTO statistics (classify, apply) VALUES ('$classify', 1)
ON DUPLICATE KEY UPDATE apply = apply + 1");
id classify apply
1 A 1
but it didn't update the existing row and it keep add another row, Where is the problem?
It's probably the column classify is not unique. You need to have a UNIQUE field in the table to make ON DUPLICATE KEY UPDATE work. If you have not set one, you can execute this statement below.
ALTER TABLE statistics ADD CONSTRAINT tb_uq UNIQUE (classify)
ON DUPLICATE KEY will update a row only when you try to insert a record that would throw a duplicate keys error (like the name states). So this happens only if you are a using a unique key or a primary key for that column. It looks like you didn't created a unique key for the classify column.
I am relatively new in php and mysql.The problem that i am facing while i inserting value in my leave table.My leave table containing following column..
1.lid(INT primary key)
2.empname(varchar)
3.username(varchar)
4.nod(INT)
5.sdate(DATE)
6.edate(DATE)
7.reason(varchar)
8.action(varchar)
9.empID (INT FOREIGN KEY)
here empID is the foreign key references from users table. The problem that im facing while inserting values into the leave table.ERROR is given below
Cannot add or update a child row: a foreign key constraint fails (db_attendance1.leave, CONSTRAINT leave_ibfk_1 FOREIGN KEY (empID) REFERENCES users (empID))
here i just send the query and here it is..
mysql_query("INSERT INTO `leave`
(`empname`, `username`,
`nod`, `sdate`, `edate`,
`reason`,`action`)
VALUES ('$empname', '$username',
'$nod', '$sdate',
'$edate', '$reason','');",
$dbCon) or die(mysql_error());
You can put
SET FOREIGN_KEY_CHECKS=0;
and run your query. Once you are done again set it back to 1 by
SET FOREIGN_KEY_CHECKS=1;
A foreign key constraint means that you one table doesn't accept inserts, updates or deletes that would 'break' the foreign key. This means, you can't update a EmpID if the new EmpID doesn't exist in the users. You can't add a new EmpID if it doesn't exist in the users table, etcetera.
So to solve this issue, you need to make sure that the EmpID you're trying to add to table 'leave', first exists in table 'users'.
Foreign keys can be a real powerful item, but can be a real pain too. Since the DB you're working on had foreign key constraints, I suggest you read on them a bit: http://en.wikipedia.org/wiki/Foreign_key
Borniet, you helped me solve my similar problem.
#OP - All I had to do to fix this was create a corresponding row in the table so that the foreign key would exist.
E.g. Table 1 has column Name
Table 2 has column friends_name, a foreign key tied to Name in table 1.
I got this error because I was trying to insert a row into table 2, where the friends_name referenced a non existing Name in table 1. So I created the name and we're off to the races :).