Update MySQL: Duplicate unique key #1062 - mysql

I have a table like this:
CREATE TABLE IF NOT EXISTS `activity` (
`ID` int(8) NOT NULL AUTO_INCREMENT,
`action` tinyint(1) NOT NULL,
`userID` int(8) NOT NULL,
`categoryID` int(8) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `UNIQUE` (`userID`,`categoryID`),
KEY `categoryID` (`categoryID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ;
With the next information:
INSERT INTO `activity` (`ID`, `action`, `userID`, `categoryID`) VALUES
(1, 2, 11, 312);
I'm trying to execute this query:
UPDATE `activity` SET `action` = '3' WHERE `userID` = '11' AND `categoryID` = '312' ;
And response me with that:
Duplicate entry '11-312' for key 'UNIQUE'
I don't know why. I ain't changing unique keys or inserting another new record. What is the problem?
Thanks.

I don't know why, when I export whole database, instead of show before SQL, show this:
CREATE TABLE IF NOT EXISTS `activity` (
`ID` int(8) NOT NULL AUTO_INCREMENT,
`action` tinyint(1) NOT NULL,
`userID` int(8) NOT NULL,
`categoryID` int(8) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `UNIQUE` (`action`,`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ;
Now I rewrite setup table sql and it works.

Related

cant add or update child row, foreign key fails

This is my sql file:
DROP DATABASE IF EXISTS `dbstudents`;
CREATE DATABASE IF NOT EXISTS `dbstudents`;
USE `dbstudents`;
DROP TABLE IF EXISTS `student_detail`;
CREATE TABLE `student_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fav_programming_language` varchar(128) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`student_detail_id` int(11) DEFAULT NULL,
`password` varchar(50) NOT NULL,
`enabled` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_DETAIL_idx` (`student_detail_id`),
CONSTRAINT `FK_DETAIL` FOREIGN KEY (`student_detail_id`) REFERENCES `student_detail` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `authorities`;
CREATE TABLE `authorities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`authority` varchar(50) NOT NULL,
UNIQUE KEY `authorities_idx_1` (`id`,`authority`),
CONSTRAINT `authorities_ibfk_1` FOREIGN KEY (`id`) REFERENCES `student` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This is insert statement:
INSERT INTO `student`
VALUES
(1, 'Stefan', 'Stefanovic', 'stefan#gmail.com', 1, 'stefan123', 1),
(2, 'Marko', 'Markovic', 'marko#gmail.com', 1, 'marko123', 1),
(3, 'Jovan', 'Jovanovic', 'jovan#gmail.com', 1, 'jovan123', 1);
This is error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`dbstudents`.`student`, CONSTRAINT `FK_DETAIL` FOREIGN KEY (`student_detail_id`) REFERENCES `student_detail` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
I found some solutions but all of them are on some way different then mine. How to solve this? An error occurs when I try to fill in every table except the autorities
As you haven't any student_details already in the system use NULL instead a number and add the number later
INSERT INTO `student`
VALUES
(1, 'Stefan', 'Stefanovic', 'stefan#gmail.com', NULL, 'stefan123', 1),
(2, 'Marko', 'Markovic', 'marko#gmail.com', NULL, 'marko123', 1),
(3, 'Jovan', 'Jovanovic', 'jovan#gmail.com', NULL, 'jovan123', 1);
see example https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=c1bbdd8ee9b9a9af244da774cdb41175

Designing E-commerce database and mysql error

I am trying to make an e-commerce site from scratch. Currently I am trying to make the database.
These are the core tables that the database will have:
Customer: which will have email, username, password....
Customers_Session: Stores information about customer session in hash
Group: basically tells what permissions a customer will have
Category: the category type of a product
Product: information about a product such as name, and description...
Product_Price: Price info on products. This will store the different prices put for each product at various times.
Product_Variation: information about product images, and various colors or styles of a product.
Customer_Orders: What products a customer has ordered.
Customer_Reviews: Reviews made by customers on a product.
Reviewed Products: This table is created based on many to many relationship between the Product table and the Review Table.
Ordered products: This table is created based on the many to many relationship between the Product and the Orders Table.
Based on the above, I have come up with the sql code below:
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`username` varchar(30) NOT NULL,
`password` varchar(64) NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`address` varchar(320) NOT NULL,
`zip` mediumint(5) NOT NULL,
`salt` varchar(40) NOT NULL,
`joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`group` tinyint(1) NOT NULL,
`dob` date NOT NULL,
`pic_url` varchar(225) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
--
-- Table structure for table `groups`
--
CREATE TABLE IF NOT EXISTS `groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`permissions` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- This is for category table
--
CREATE TABLE IF NOT EXISTS `category`(
`category_id` tinyint(3) NOT NULL AUTO_INCREMENT,
`category_type` varchar(100) NOT NULL,
`category_description` varchar(160) NOT NULL,
PRIMARY KEY (`category_id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
--
-- This is for product table
--
CREATE TABLE IF NOT EXISTS `products`(
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(100) NOT NULL UNIQUE,
`product_description` varchar(160) NOT NULL,
`quantity` int(5) NOT NULL,
`product_code` varchar(4) NOT NULL,
`keywords` varchar(70) NOT NULL,
`category_id` tinyint(3),
PRIMARY KEY (`product_id`),
INDEX (`category_id`),
CONSTRAINT FOREIGN KEY (`category_id`) REFERENCES category(`category_id`) ON DELETE SET NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
--
--
-- Table structure for table `bookings`
--
CREATE TABLE IF NOT EXISTS `bookings` (
`bookings_id` int(11) NOT NULL AUTO_INCREMENT,
`party_type` varchar(50) NOT NULL,
`location` varchar(100) NOT NULL,
`day` varchar(10) NOT NULL,
`time` smallint(6) NOT NULL,
`people_count` smallint(6) NOT NULL,
`booking_name` varchar(50) NOT NULL,
`booking_email` varchar(50) NOT NULL,
PRIMARY KEY (`bookings_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='This is for the bookings' AUTO_INCREMENT=1 ;
--
-- Dumping data for table `groups`
--
INSERT INTO `groups` (`id`, `name`, `permissions`) VALUES
(1, 'Administrator', '{"admin":1}'),
(2, 'Users', '{"users":2}');
--
-- Table Structure for Reviews
--
CREATE TABLE IF NOT EXISTS `customer_reviews`(
`reviews_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11),
`rating` int(5) NOT NULL,
`comment` varchar(160) NOT NULL,
PRIMARY KEY(`reviews_id`),
INDEX (`user_id`),
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES users(`user_id`) ON DELETE SET NULL
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
--
-- Table structure for reviewed products This is a many relationshi btw reviews table and product
--
CREATE TABLE IF NOT EXISTS `reviewed_products`(
`product_id` int(11),
`reviews_id`int(11),
PRIMARY KEY(`product_id`,`reviews_id`),
CONSTRAINT FOREIGN KEY(`product_id`) REFERENCES products(`product_id`) ON DELETE SET NULL,
CONSTRAINT FOREIGN KEY(`reviews_id`) REFERENCES customer_reviews(`reviews_id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='This is for many to many cardinality btw reviews and products' AUTO_INCREMENT=1 ;
--
--
-- Table structure for table `orders`
--
CREATE TABLE IF NOT EXISTS `customer_orders` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`order_time` int(11) NOT NULL,
`amount` int(5),
`confirmation_number` int(,
`user_id` int(11),
`product_id` int(11),
PRIMARY KEY (`order_id`),
INDEX (`user_id`),
CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES users(`user_id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
/* We need a new table since the customer_order and product is in a many to many relationship */
--
--
-- Table structure for table `curtomer_order_product`
--
CREATE TABLE IF NOT EXISTS `ordered_product`(
`product_id` int(11),
`order_id` int(11),
`quantity` smallint(5),
PRIMARY KEY(`product_id`,`order_id`),
INDEX (`product_id`,`order_id`),
CONSTRAINT FOREIGN KEY (`order_id`) REFERENCES customer_orders(`order_id`) ON DELETE RESTRICT,
CONSTRAINT FOREIGN KEY (`product_id`) REFERENCES products(`product_id`) ON DELETE RESTRICT
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- This is for price table
--
CREATE TABLE IF NOT EXISTS `product_price`(
`price_id` int(11) NOT NULL AUTO_INCREMENT,
`price` decimal(6,2) NOT NULL,
`product_id` int(11) NOT NULL,
PRIMARY KEY (`price_id`),
INDEX (`product_id`),
CONSTRAINT FOREIGN KEY (`product_id`) REFERENCES products(`product_id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
--
-- Table structure for table `product_variations`
--
CREATE TABLE IF NOT EXISTS `product_variations`(
`variations_id` int(11) NOT NULL AUTO_INCREMENT,
`color_name` varchar(10) NOT NULL,
`color_value` char(6) NOT NULL,
`product_id` int(11),
`picture1` varchar(100) NOT NULL,
`picture2` varchar(100) NOT NULL,
`picture3` varchar(100) NOT NULL,
PRIMARY KEY (`variations_id`),
INDEX (`product_id`),
CONSTRAINT FOREIGN KEY (`product_id`) REFERENCES products(`product_id`) ON DELETE RESTRICT
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
--
-- Table structure for table `users_session`
--
CREATE TABLE IF NOT EXISTS `users_session` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`hash` varchar(64) NOT NULL,
PRIMARY KEY (`id`),
INDEX (`user_id`),
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES users(`user_id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The problem is that when I try to run the above code in PHPmyadmin, I get an error stating "Cannot add foreign key constraint". This starts to happen when creating the customer_Reviews table and any other subsequent tables that require foreign keys.
My questions are:
1. Would you recommend designing the database this way.
2. Why am I getting the "Cannot add foreign key constraint" error?
Thanks.
For a full quality review of your database design, you might try the Code Review sister site. At a glance, I don't see any glaring issues with your database design or your SQL.
The foreign key constraint is failing because you have misnamed the column in question.
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES users(`user_id`)
should be:
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES users(`id`)

how to get autoincrement ID of one table and insert in another table

I have a mysql table whose description is given below
Create Table
CREATE TABLE `question` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`category` varchar(255) DEFAULT NULL,
`is_deleted` bit(1) NOT NULL,
`question` varchar(255) DEFAULT NULL,
`version` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8
I have another table
Create Table
CREATE TABLE `parent_question` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`is_deleted` bit(1) NOT NULL,
`version` int(11) DEFAULT NULL,
`pid` bigint(20) NOT NULL,
`qid` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK8FEA83DBE860AF9` (`pid`),
KEY `FK8FEA83DBF34C20F6` (`qid`),
CONSTRAINT `FK8FEA83DBE860AF9` FOREIGN KEY (`pid`) REFERENCES `parent` (`id`),
CONSTRAINT `FK8FEA83DBF34C20F6` FOREIGN KEY (`qid`) REFERENCES `question` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8
I have the right to insert one row in the question table.So when I add a new row then id will be generated (because it is auto_increment) and I want to store this id in the qid field parent_question table.
Can anybody please tell me how to do it?
Use the last_insert_id() function:
insert into question values (...);
insert into parent_question values (..., last_insert_id(), ...);

PHPMyAdmin - InnoDB tables will not join

This is my database structure:
CREATE database mytvguide
CREATE TABLE IF NOT EXISTS `channels` (
`id` int(11) NOT NULL auto_increment,
`channel1` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `episodeairings` (
`id` mediumint(255) unsigned NOT NULL auto_increment,
`programme` varchar(255) collate utf8_unicode_ci NOT NULL,
`channel` varchar(255) collate utf8_unicode_ci default NULL,
`airdate` datetime default NULL,
`displayair` datetime default NULL,
`expiration` datetime default NULL,
`epname` varchar(256) collate utf8_unicode_ci NOT NULL,
`epno` mediumint(255) unsigned NOT NULL,
`epseries` mediumint(255) unsigned NOT NULL,
`setreminder` varchar(255) collate utf8_unicode_ci default NULL,
PRIMARY KEY (`id`),
KEY `channel` (`channel`),
KEY `programme` (`programme`),
KEY `setreminder` (`setreminder`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC AUTO_INCREMENT=3 ;
INSERT INTO `episodeairings` (`id`, `programme`, `channel`, `airdate`, `displayair`, `expiration`, `epname`, `setreminder`) VALUES
(1, 'TV Programme 1', 'ITV2', '2011-07-09 22:35:00', '2011-06-30 22:35:00', '2011-06-30 23:05:00', 'Episode', '' , '', NULL),
(2, 'TV Programme 1', 'ITV2', '2011-07-10 02:25:00', '2011-07-01 02:25:00', '2011-07-01 02:55:00', 'EpisodeTest', '1', '2', NULL);
CREATE TABLE IF NOT EXISTS `episode` (
`id` int(11) NOT NULL auto_increment,
`epname` varchar(255) NOT NULL,
`seriesnumber` int(11) NOT NULL,
`episodenumber` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `epname` (`epname`),
KEY `seriesnumber` (`seriesnumber`),
KEY `episodenumber` (`episodenumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `episode` (`id`, `epname`, `seriesnumber`, `episodenumber`) VALUES
(1, 'Episode', 1, 1);
CREATE TABLE IF NOT EXISTS `programme1` (
`id` int(11) NOT NULL auto_increment,
`programme` varchar(255) NOT NULL default 'Police, Camera, Action!',
PRIMARY KEY (`id`),
KEY `programme` (`programme`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `programme1` (`id`, `programme`) VALUES
(1, 'TV Programme 1');
INSERT INTO `channels` (`id`, `channel`) VALUES
(1, 'ITV2');
For some reason I can't link any of the tables in episodeairings - namely programme, channel, airdate, epname, epno, epseries with those in the other tables
(which are programme, epname, seriesnumber, episodenumber).
Basically, the dropdown won't happen at all for linked tables, as it should do.
This is despite the fact my database is stored as InnoDB via PHPmyadmin and I set the linked tables.
Why is this and how can I fix it?
I am not sure how phpmyadmin works but I would assume that it requires you to define some foreign key constraints between your tables (e.g. using the alter table statement).
See alter table docs: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

How to optimize this mysql query - explain output included

This is the query (a search query basically, based on tags):-
select
SUM(DISTINCT(ttagrels.id_tag in (2105,2120,2151,2026,2046) )) as key_1_total_matches, td.*, u.*
from Tutors_Tag_Relations AS ttagrels
Join Tutor_Details AS td ON td.id_tutor = ttagrels.id_tutor
JOIN Users as u on u.id_user = td.id_user
where (ttagrels.id_tag in (2105,2120,2151,2026,2046)) group by td.id_tutor HAVING key_1_total_matches = 1
And following is the database dump needed to execute this query:-
CREATE TABLE IF NOT EXISTS `Users` (
`id_user` int(10) unsigned NOT NULL auto_increment,
`id_group` int(11) NOT NULL default '0',
PRIMARY KEY (`id_user`),
KEY `Users_FKIndex1` (`id_group`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=730 ;
INSERT INTO `Users` (`id_user`, `id_group`) VALUES
(303, 1);
CREATE TABLE IF NOT EXISTS `Tutor_Details` (
`id_tutor` int(10) unsigned NOT NULL auto_increment,
`id_user` int(10) NOT NULL default '0',
PRIMARY KEY (`id_tutor`),
KEY `Users_FKIndex1` (`id_user`),
KEY `id_user` (`id_user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;
INSERT INTO `Tutor_Details` (`id_tutor`, `id_user`) VALUES
(26, 303);
CREATE TABLE IF NOT EXISTS `Tags` (
`id_tag` int(10) unsigned NOT NULL auto_increment,
`tag` varchar(255) default NULL,
PRIMARY KEY (`id_tag`),
UNIQUE KEY `tag` (`tag`),
KEY `id_tag` (`id_tag`),
KEY `tag_2` (`tag`),
KEY `tag_3` (`tag`),
KEY `tag_4` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2957 ;
INSERT INTO `Tags` (`id_tag`, `tag`) VALUES
(2026, 'Brendan.\nIn'),
(2046, 'Brendan.'),
(2105, 'Brendan'),
(2120, 'Brendan''s'),
(2151, 'Brendan)');
CREATE TABLE IF NOT EXISTS `Tutors_Tag_Relations` (
`id_tag` int(10) unsigned NOT NULL default '0',
`id_tutor` int(10) unsigned default NULL,
`tutor_field` varchar(255) default NULL,
`cdate` timestamp NOT NULL default CURRENT_TIMESTAMP,
`udate` timestamp NULL default NULL,
KEY `Tutors_Tag_Relations` (`id_tag`),
KEY `id_tutor` (`id_tutor`),
KEY `id_tag` (`id_tag`),
KEY `id_tutor_2` (`id_tutor`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `Tutors_Tag_Relations` (`id_tag`, `id_tutor`, `tutor_field`, `cdate`, `udate`) VALUES
(2105, 26, 'firstname', '2010-06-17 17:08:45', NULL);
ALTER TABLE `Tutors_Tag_Relations`
ADD CONSTRAINT `Tutors_Tag_Relations_ibfk_2` FOREIGN KEY (`id_tutor`) REFERENCES `Tutor_Details` (`id_tutor`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `Tutors_Tag_Relations_ibfk_1` FOREIGN KEY (`id_tag`) REFERENCES `Tags` (`id_tag`) ON DELETE NO ACTION ON UPDATE NO ACTION;
What the query does?
This query actually searches tutors which contain "Brendan"(as their name or biography or something). The id_tags 2105,2120,2151,2026,2046 are nothing but the tags which are LIKE "%Brendan%".
My question is :-
1.In the explain of this query, the reference column shows NULL for ttagrels, but there are possible keys (Tutors_Tag_Relations,id_tutor,id_tag,id_tutor_2). So, why is no key being taken. How to make the query take references. Is it possible at all?
2. The other two tables td and u are using references. Any indexing needed in those? I think not.
Check the explain query output here
http://www.test.examvillage.com/explain.png
Don't analyze performance of database with single record in table. Create at least 100 records.