mysql insert error 1062 - mysql

SQL query:
INSERT INTO `website_categorization`.`category_keyword` (
`ID` ,
`ID_Category` ,
`Keyword` ,
`Score`)
VALUES (
NULL , '18', 'free mail', ''
), (
NULL , '18', 'web email free', ''
)
MySQL said:
#1062 - Duplicate entry '18-free mail' for key 'ID_Category'
It shows this duplicate entry error even though there is no entry at row no 1062. ( ID is primary key, and unique(ID_Category,Keyword) ).
Can u help me in this?...

You already have a row in your database with the values '18' and 'free mail'. You can't have two such rows because of the unique constraint. You have some choices:
Remove the original row and try your insert again: DELETE FROM yourtable WHERE ID_Category = '18' AND Keyword = 'free mail'.
Remove the unique constraint to allow both rows to exist.
Use INSERT IGNORE to ignore the error.
Use REPLACE instead of INSERT to replace the old row with the new row.
Attempt the INSERT knowing that the client-side will be alerted of the error.

Well, it means that the data you are inserting breaks the unique constraints. From the error messasge I'd say some data already exists with the pair (18, 'free mail') - you say that is constrained to be unique.
The row number is not an indication, because it doesn't correspond to the key.

Your ID_category key is declared as unique and thus you cannot have two entries with the same value.

If your ID field is truly a primary key, it is mostly likely (or should be) auto-incremented. So leave that field out of the INSERT query.

That is MySQL Error number 1062, not row number. The error means duplicate entry. You are inserting NULL and '18' twice in ID and ID_Category respectively, so it will throw this error the 2nd time you do it. ID_Category is very likely the name of your index. You can do a
show index from website_categorization.category_keyword
to see the index name.

Related

Copying a foreign key value in an row generation trigger

I'm trying to build a trigger that will auto-fill information into tblRegistrations when a new entry is created in tblAttendees and I'm unsure what I should be using to get it to take the new Auto-incremented key from the tblAttendees?
So in the code Registration ID is the primary key auto_incremented for tblRegistrations and AttendeeID is the primary key auto_incremented for tblattendees which exists as a foreign key on tblRegistrations
CREATE TRIGGER trgRegistration 
AFTER INSERT ON tblattendees 
FOR EACH ROW 
INSERT INTO tblregistration (RegistrationID, AttendeeID, EventID, RegistrationDate, RegistrationPaid)
VALUES (AUTO_INCREMENT, AUTO_INCREMENT, '3', CURRENT_DATE, '0')
When I try to end a new entry into the attendees table to test the trigger I keep getting this error:
"#1054- Unknown Column 'Auto_Increment' in 'field list'
Clearly it's a problem with how I have by Values formatted, but I'm uncertain on how to proceed.
The AUTO_INCREMENT column RegistrationID should take care of itself if you put NULL there or just leave it out of the column list.
As for the newly-generated AttendeeID, you can access that using the NEW keyword, which stands for the newly-inserted row that caused the trigger to run.
CREATE TRIGGER trgRegistration
AFTER INSERT ON tblattendees
FOR EACH ROW
INSERT INTO tblregistrations (AttendeeID, EventID, RegistrationDate, RegistrationPaid)
VALUES (NEW.AttendeeID, '3', CURRENT_DATE, '0');

How to do an on duplicate key update statement

I have this SQL statement for inserting data into my database, I just need to update instead when a duplicate value is entered, how can I do this do I need to use the primary key or can I use a specific value
The auto_incremented column that you see is the primary key called license_id
SQL CODE
INSERT INTO License
(license_id,
license_number,
start_date,
end_date,
duration,
expiry_date)
VALUES
('5',
'00005555',
'2015-11-22',
'2015-11-23',
'1',
'2015-11-24')
on duplicate key update ????
What do I fill in by the question marks
I just done something like this, it didnt work
INSERT INTO License
(license_id,
license_number,
start_date,
end_date,
duration,
expiry_date)
VALUES
('5',
'00005555',
'2015-11-23',
'2015-11-24',
'1',
'2015-11-25')
on duplicate key update license_id = values(license_id)
There is no point in doing on duplicate key update license_id = values(license_id) because the license_id you're trying to insert already exists in the table and it would just change the license_id of an existing record to the same value as before. Rather, the on duplicate key update is intended to update the other values. In your case it could maybe be, for example,
on duplicate key update
license_number = values(license_number)
start_date = values(start_date),
end_date = values(end_date),
duration = values(duration),
expiry_date = values(expiry_date);
I found how to do it, i tried without the primary key and the database just got confused, it entered a new record so I did this, used a different table
INSERT INTO Product (product_id,product_name, version) VALUES ('1', 'nfinityX', '5')
on duplicate key update product_id='1', product_name='infinity', version='5';
There is alot of related code that you have not seen, which makes it hard for you guys to understand the context of what I mean, but this seams to have worked, as you can see above.
I had that record already, and tested what I wrote above and it worked, I had to put primary key so it knows what row to update, otherwise it will update other rows and get confused. Is this the right way, I dont know.

Broken auto_increment on primary key?

I have no idea how to fix this, I've dumped and recreated the database (per an answer somewhere else), tried manually inserting 128 ... and tried just deleting 127 and tried again. :/ Can't figure it out.
Copied this from the query I just tried:
INSERT INTO `bestofthebest2`.`Topics` (`topicid`, `category`, `topic`)
VALUES ('128', '', ''), (NULL , '', '')
MySQL said: Documentation
#1062 - Duplicate entry '127' for key 'topicid'
Is the data type of topicid a TINYINT by chance? The maximum value a signed tinyint can hold is 127. Additionally, MySQL has a rather odd (in my opinion) overflow behavior in that it simply rounds down overflows rather than erroring. What's happening is that it's trying to increment to 128, but that overflows, so it gets changed to 127. Since 127 already exists, it errors.
This can be easily recreated:
CREATE TABLE test ( id TINYINT AUTO_INCREMENT PRIMARY KEY );
INSERT INTO test (id) VALUES (128);
-- A select will show you a row with id = 127
INSERT INTO test (id) VALUES (128);
-- ERROR 1062 (23000): Duplicate entry '127' for key 'PRIMARY'
The simplest fix is to use a bigger data type. A signed integer will afford you 2^31-1 values, so unless you plan on having more than 2 billionish topics, it should work well:
ALTER TABLE bestofthebest2 CHANGE topicid topicid INT NOT NULL;
First:
SELECT MAX(topicid)+1 FROM `bestofthebest2`.`Topics`;
Then with the result as $RESULT:
ALTER TABLE `bestofthebest2`.`Topics` AUTO_INCREMENT = $RESULT;

MySQL 5.5.24 - Duplicate entry on UPDATE, when there's no real duplicate

I have to update a table with the following structure:
CREATE TABLE `eav_entity_attribute` (
`entity_attribute_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Entity Attribute Id',
`entity_type_id` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT 'Entity Type Id',
`attribute_set_id` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT 'Attribute Set Id',
`attribute_group_id` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT 'Attribute Group Id',
`attribute_id` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT 'Attribute Id',
`sort_order` smallint(6) NOT NULL DEFAULT '0' COMMENT 'Sort Order',
PRIMARY KEY (`entity_attribute_id`),
UNIQUE KEY `UNQ_EAV_ENTITY_ATTRIBUTE_ATTRIBUTE_SET_ID_ATTRIBUTE_ID` (`attribute_set_id`,`attribute_id`),
UNIQUE KEY `UNQ_EAV_ENTITY_ATTRIBUTE_ATTRIBUTE_GROUP_ID_ATTRIBUTE_ID` (`attribute_group_id`,`attribute_id`),
KEY `IDX_EAV_ENTITY_ATTRIBUTE_ATTRIBUTE_SET_ID_SORT_ORDER` (`attribute_set_id`,`sort_order`),
KEY `IDX_EAV_ENTITY_ATTRIBUTE_ATTRIBUTE_ID` (`attribute_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Eav Entity Attributes'
Above table contains a single row:
INSERT INTO `eav_entity_attribute`
(`entity_attribute_id`, `entity_type_id`, `attribute_set_id`, `attribute_group_id`, `attribute_id`, `sort_order`)
VALUES
(32758, 4, 224, 3423, 5171, 12)
I'm running an automatic import procedure, which will read an external source of data and write into this table.
This import runs multiple times and, therefore, sometimes the same data is imported several times. In such case, the procedure simply overwrites the old data with the new one, even when the new one is identical to the old. The condition where the same data exists is handled with an ON DUPLICATE KEY UPDATE clause. This works almost perfectly, except on this specific table.
On this table, when the procedure attempts an UPDATE, I receive a "Duplicate key" message, which I can't explain. I debugged the code, and this is the query that fails (extracted from the INSERT..ON DUPLICATE KEY):
UPDATE eav_entity_attribute
SET
`attribute_group_id` = 3423
,`attribute_id` = 5171
,`attribute_set_id` = 223
,`entity_type_id` = 4
,`sort_order` = 320
WHERE
(`attribute_group_id` = 3423) AND
(`attribute_id` = 5171)
The error is the following:
Error Code: 1062. Duplicate entry '3423-5171' for key 'UNQ_EAV_ENTITY_ATTRIBUTE_ATTRIBUTE_GROUP_ID_ATTRIBUTE_ID'
I know that the pair 3423-5171 already exists, but the UPDATE would replace these values with themselves, not create a new entry. I'm quite confused about the cause of this issue, any suggestion would be very welcome. Thanks.
Update - New finding
I got some sort of "inspiration" and I made an experiment. I removed the Unique constraint involving on (attribute_set_id,attribute_id) (note, this is not the one in the error) and I ran the INSERT..ON DUPLICATE query. It worked perfectly.
Mine is a conjecture, but this is what I think: the data I'm trying to write to the table clashes with two constraints:
UNIQUE(attribute_set_id,attribute_id)
UNIQUE(attribute_group_id,attribute_id)
The INSERT fails, presumably because of the duplication error raised by the first constraint. This triggers the UPDATE, which uses the first constraint as the implicit WHERE clause. My speculation is that, in such case, the first constraint is somehow ignored, but the UPDATE trips over the second, which didn't get involved earlier.
This still doesn't seem, to me, a valid reason for an UPDATE which replaces something with itself to raise a duplicate entry error, but it may shed some light on the logic behind it.
Second Update
I found out that the table I was testing against actually contains a lot of rows (I forgot to disable the filtered view) resulting from the successful import of other data. However, the "duplicate candidate" is still unique in the set.
I confirm what posted in the comments, when the table contains only that rows, the INSERT..ON DUPLICATE works, as well as the UPDATE alone. Now I'm wondering why does the table get messed up when there is more data in it, since we are still talking about a single unique row being updated with the same data.
Third Update - Found the root cause
I finally found out the reason why the UPDATE fails, now I have to find out how do I get in such condition.
The clue was my conjecture in the first update. Simply, I have two very similar rows (please note I'm using different values as I started from a clean database).
row,entity_attribute_id,entity_type_id,attribute_set_id,attribute_group_id,attribute_id,sort_order
1,16919, 4, 120, 1746, 80, 1
2,16649, 4, 119, 1744, 80, 210
Here's what happens:
The INSERT attempts to insert a row with the following values: 120, 4, 1744, 80, 54.
This triggers the "duplicate key", since the values 120, 80 are a duplicate for the fields attribute_set_id, attribute_id (row 1).
MySQL then tries the UPDATE, which becomes as follows:
UPDATE table
entity_type_id = 4
,attribute_group_id = 1744
,sort_order = 54
WHERE
(attribute_set_id = 120) AND (attribute_id = 80)
This time, the UPDATE fails because the values 1744,80 are violate the constraint on the pair attribute_group_id, attribute_id, found in row 2.
In summary
The INSERT fails because row 1 has the same values for the key attribute_set_id, attribute_id.
The UPDATE fails because row 2 has the same values for the key attribute_group_id, attribute_id.
Solution
I will have to review the whole import procedure, as, in theory, none of such duplicates should arise. MySQL is doing its job fine, it's the database that is complicated.
Thanks for all the suggestions.
Try not to update key values within UPDATE clause of INSERT ... ON DUPLICATE KEY UPDATE. It is strange to ask MySQL to change key values if a record with these key values already exist, so, unexpected behavoiur of MySQL is not surprising.

MySQL: Insert on duplicate update problem with primary key

I'm running the following query... the issue I'm running into is that it saves the id field properly with rows 0-27 but then it tries to duplicate row 0. Any thoughts on why this is trying to duplicate row 0?
INSERT INTO
deal (`id`, `site_id`)
VALUES (NULL, 1)
ON DUPLICATE KEY UPDATE `id` = NULL,`site_id` = 1
From the manual:
You can also explicitly assign NULL or 0 to the column to generate sequence numbers.
So, effectivly, entering (0,'whatever') is seen as ('the next autoincrement id','whatever'). No duplicate key issues as far as MySQL is concerned. You can bypass this by using NO_AUTO_VALUE_ON_ZERO. Note that using 0 as an identifier is not recommended practice.
A PRIMARY KEY can't be NULL in MySQL, so your UPDATE id = NULL is casted to UPDATE id = 0.
See also: http://www.xaprb.com/blog/2009/09/12/the-difference-between-a-unique-index-and-primary-key-in-mysql/