PHPMyAdmin - InnoDB tables will not join - mysql

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

Related

MySQL joining 2 tables in to one main table

I have 2 tables 'cat' and 'sub_cat' and these two tables should join or something with main table 'product'
I tried all joining methods and non of them gave me right result I want.
I'm sure there is a method. I don't know what to call.
Sample SQL
This is how the last query should be
forget about the normalization theories and every thing and I just want the last query to be like this or mysql method that I can use on this.
cat_id cannot be duplicate
s_id should also cannot be duplicate
like in third row there can be: cat_id but no s_id the s_id should be null
if there is no cat_id and no s_id both should be null like fourth row
p_id can be duplicate
can't use group by or distinct cause it doesn't give null values then as i know
only method i got closer is using left joining both cat and sub_cat to prod table but it gives me duplicate cat_id and s_id and can't use group by or distinct on this cause there should be null values.
here is the test data
CREATE TABLE IF NOT EXISTS `cat` (
`product_id` int(11) DEFAULT NULL,
`cat_id` int(11) DEFAULT NULL,
`cat_name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `cat` (`product_id`, `cat_id`, `cat_name`) VALUES
(1, 1, 'cat1'),
(2, 2, 'cat2'),
(3, 3, 'cat3'),
(1, 4, 'ca4');
CREATE TABLE IF NOT EXISTS `prod` (
`product_id` int(11) DEFAULT NULL,
`name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `prod` (`product_id`, `name`) VALUES
(1, 'prod1'),
(2, 'prod2'),
(3, 'pro3'),
(4, 'prod4');
CREATE TABLE IF NOT EXISTS `sub_cat` (
`product_id` int(11) DEFAULT NULL,
`sub_cat_id` int(11) DEFAULT NULL,
`sub_cat_name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `sub_cat` (`product_id`, `sub_cat_id`, `sub_cat_name`) VALUES
(1, 1, 'sub cat 1'),
(2, 2, 'sub cat 2'),
(1, 3, 'sub3');
I have done a similar thing in this one.prop_cat acts as you Category table,prop_subcat as your subcategory table and property as you product.
CREATE TABLE `prop_cat` (
`pcat_id` int(11) NOT NULL AUTO_INCREMENT,
`pcat_name` varchar(60) DEFAULT NULL,
PRIMARY KEY (`pcat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `prop_subcat` (
`psubcat_id` int(11) NOT NULL,
`pcat_id` int(11) NOT NULL,
`psubcat_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`psubcat_id`,`pcat_id`),
KEY `pspc_idx` (`pcat_id`),
CONSTRAINT `catsub` FOREIGN KEY (`pcat_id`) REFERENCES `prop_cat` (`pcat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `property` (
`prop_id` int(11) NOT NULL AUTO_INCREMENT,
`prop_name` varchar(25) DEFAULT NULL,
`price` double DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`image` varchar(60) DEFAULT NULL,
`area` double DEFAULT NULL,
`psubcat_id` int(11) DEFAULT NULL,
`description` text,
PRIMARY KEY (`prop_id`),
KEY `psub_idx` (`psubcat_id`),
CONSTRAINT `psub` FOREIGN KEY (`psubcat_id`) REFERENCES `prop_subcat` (`pcat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
SELECT
prop_cat.`pcat_id` AS prop_cat_pcat_id,
prop_cat.`pcat_name` AS prop_cat_pcat_name,
prop_subcat.`psubcat_id` AS prop_subcat_psubcat_id,
prop_subcat.`pcat_id` AS prop_subcat_pcat_id,
prop_subcat.`psubcat_name` AS prop_subcat_psubcat_name,
property.`prop_id` AS property_prop_id,
property.`prop_name` AS property_prop_name,
property.`price` AS property_price,
property.`location` AS property_location,
property.`image` AS property_image,
property.`area` AS property_area,
property.`psubcat_id` AS property_psubcat_id,
property.`description` AS property_description
FROM
`prop_cat` prop_cat INNER JOIN `prop_subcat` prop_subcat ON prop_cat.`pcat_id` = prop_subcat.`pcat_id`
INNER JOIN `property` property ON prop_subcat.`pcat_id` = property.`psubcat_id`

Cannot delete foreign key constraint fails

When I try to delete the question from the test, the sql show :
`Cannot delete or update a parent row: a foreign key constraint fails (`oes`.`studentquestion`,
CONSTRAINT `studentquestion_ibfk_2` FOREIGN KEY (`testid`, `qnid`) REFERENCES `question`
(`testid`, `qnid`))`
Here will be my table:
student table
CREATE TABLE `student` (
`stdid` bigint(20) NOT NULL,
`subid` int(11) NOT NULL,
`stdname` varchar(40) default NULL,
`stdpassword` varchar(40) default NULL,
`emailid` varchar(40) default NULL,
`contactno` varchar(20) default NULL,
`address` varchar(40) default NULL,
`city` varchar(40) default NULL,
`pincode` varchar(20) default NULL,
PRIMARY KEY (`stdid`),
UNIQUE KEY `stdname` (`stdname`),
UNIQUE KEY `emailid` (`emailid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
studentquestion table
CREATE TABLE `studentquestion` (
`stdid` bigint(20) NOT NULL default '0',
`testid` bigint(20) NOT NULL default '0',
`qnid` int(11) NOT NULL default '0',
`answered` enum('answered','unanswered','review') DEFAULT NULL,
`stdanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
PRIMARY KEY (`stdid`,`testid`,`qnid`),
KEY `testid` (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
studenttest table
`stdid` bigint(20) NOT NULL default '0',
`testid` bigint(20) NOT NULL default '0',
`starttime` timestamp NOT NULL default CURRENT_TIMESTAMP,
`endtime` timestamp NOT NULL default '0000-00-00 00:00:00',
`correctlyanswered` int(11) default NULL,
`status` enum('over','inprogress') default NULL,
PRIMARY KEY (`stdid`,`testid`),
KEY `testid` (`testid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
question table
CREATE TABLE `question` (
`testid` bigint(20) NOT NULL default '0',
`qnid` int(11) NOT NULL default '0',
`question` varchar(500) default NULL,
`optiona` varchar(100) DEFAULT NULL,
`optionb` varchar(100) DEFAULT NULL,
`optionc` varchar(100) DEFAULT NULL,
`optiond` varchar(100) DEFAULT NULL,
`correctanswer` enum ('optiona','optionb','optionc','optiond') DEFAULT NULL,
`marks` int(11) DEFAULT NULL,
PRIMARY KEY (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
test table
CREATE TABLE `test` (
`testid` bigint(20) NOT NULL,
`testname` varchar(30) NOT NULL,
`testdesc` varchar(100) default NULL,
`testdate` date default NULL,
`testtime` time default NULL,
`subid` int(11) default NULL,
`testfrom` timestamp NOT NULL default CURRENT_TIMESTAMP,
`testto` timestamp NOT NULL default '0000-00-00 00:00:00',
`duration` int(11) default NULL,
`totalquestions` int(11) default NULL,
`attemptedstudents` bigint(20) DEFAULT NULL,
`testcode` varchar(40) NOT NULL,
`tcid` bigint(20) default NULL,
`minimunscore` int(11) NOT NULL,
PRIMARY KEY (`testid`),
UNIQUE KEY `testname` (`testname`),
KEY `test_fk1` (`subid`),
KEY `test_fk2` (`tcid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
subject table
CREATE TABLE `subject` (
`subid` int(11) NOT NULL,
`subname` varchar(40) default NULL,
`subdesc` varchar(100) default NULL,
`tcid` bigint(20) default NULL,
PRIMARY KEY (`subid`),
UNIQUE KEY `subname` (`subname`),
KEY `subject_fk1` (`tcid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `studentquestion`
ADD CONSTRAINT `studentquestion_ibfk_1` FOREIGN KEY (`stdid`) REFERENCES `student`
(`stdid`),
ADD CONSTRAINT `studentquestion_ibfk_2` FOREIGN KEY (`testid`, `qnid`) REFERENCES `question`
(`testid`, `qnid`);
ALTER TABLE `studenttest`
ADD CONSTRAINT `studenttest_ibfk_1` FOREIGN KEY (`stdid`) REFERENCES `student` (`stdid`),
ADD CONSTRAINT `studenttest_ibfk_2` FOREIGN KEY (`testid`) REFERENCES `test` (`testid`);
ALTER TABLE `question`
ADD CONSTRAINT `question_ibfk_1` FOREIGN KEY (`testid`) REFERENCES `test` (`testid`);
ALTER TABLE `test`
ADD CONSTRAINT `test_fk1` FOREIGN KEY (`subid`) REFERENCES `subject` (`subid`),
ADD CONSTRAINT `test_fk2` FOREIGN KEY (`tcid`) REFERENCES `testconductor` (`tcid`);
ALTER TABLE `subject`
ADD CONSTRAINT `subject_fk1` FOREIGN KEY (`tcid`) REFERENCES `testconductor` (`tcid`);
INSERT INTO `adminlogin` VALUES ('001','root','root');
INSERT INTO `studenttest` (`stdid`, `testid`, `starttime`, `endtime`, `correctlyanswered`,
`status`) VALUES
(1, 1, '2014-10-15 09:11:24', '2014-10-15 09:21:24', 0, 'over');
INSERT INTO `subject` (`subid`, `subname`, `subdesc`, `tcid`) VALUES
(1, 'fref', 'few', NULL);
INSERT INTO `test` (`testid`, `testname`, `testdesc`, `testdate`, `testtime`, `subid`,
`testfrom`, `testto`, `duration`, `totalquestions`, `attemptedstudents`, `testcode`, `tcid`)
VALUES
(1, 'gregre', 'greger', '2014-10-15', '17:08:16', 1, '2014-10-15 03:08:16', '2014-10-16
15:59:59', 10, 2, 0, '.ȁ', NULL);
When the student has complete the test, then the question will not be able to delete. Neither the test or subject.
It is because the studentquestion table will be left with a foreign key that points to a non existent record. You'll either need to remove rows which have a foreign key to the record you want to delete or, alternatively set up CASCADE rules so that when parent rows are deleted action can be taken.

Foreign Key Constraint error for delete data form table

i am doing a project on ONLINE EXAMINATION which is copied from my senior but while execute i got some error. attach my code here and the error msg.
table #:
CREATE TABLE IF NOT EXISTS `question` (
`testid` bigint(20) NOT NULL DEFAULT '0',
`qnid` int(11) NOT NULL DEFAULT '0',
`question` varchar(500) DEFAULT NULL,
`optiona` varchar(100) DEFAULT NULL,
`optionb` varchar(100) DEFAULT NULL,
`optionc` varchar(100) DEFAULT NULL,
`optiond` varchar(100) DEFAULT NULL,
`correctanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
`marks` int(11) DEFAULT NULL,
PRIMARY KEY (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table question
INSERT INTO `question` (`testid`, `qnid`, `question`, `optiona`, `optionb`, `optionc`, `optiond`, `correctanswer`, `marks`) VALUES
(1, 1, 'why use photoshop', 'image retouching', 'image making', 'image destroying', 'color coreection', 'optiona', 1),
(2, 1, 'java is', 'fish fry', 'software language', 'programing language', 'web maker', 'optionc', 1),
(2, 2, 'what is vaja', 'bengali', 'kokl', 'khsd', 'kojsgf', 'optiona', 1);
Table ###
--
-- Table structure for table student
CREATE TABLE IF NOT EXISTS `student` (
`stdid` bigint(20) NOT NULL,
`stdname` varchar(40) DEFAULT NULL,
`stdpassword` varchar(40) DEFAULT NULL,
`emailid` varchar(40) DEFAULT NULL,
`contactno` varchar(20) DEFAULT NULL,
`address` varchar(40) DEFAULT NULL,
`city` varchar(40) DEFAULT NULL,
`pincode` varchar(20) DEFAULT NULL,
PRIMARY KEY (`stdid`),
UNIQUE KEY `stdname` (`stdname`),
UNIQUE KEY `emailid` (`emailid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table studentquestion
CREATE TABLE IF NOT EXISTS `studentquestion` (
`stdid` bigint(20) NOT NULL DEFAULT '0',
`testid` bigint(20) NOT NULL DEFAULT '0',
`qnid` int(11) NOT NULL DEFAULT '0',
`answered` enum('answered','unanswered','review') DEFAULT NULL,
`stdanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
PRIMARY KEY (`stdid`,`testid`,`qnid`),
KEY `testid` (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Constraints for table `question`
--
ALTER TABLE `question`
ADD CONSTRAINT `question_ibfk_1` FOREIGN KEY (`testid`) REFERENCES `test` (`testid`);
--
-- Constraints for table `studentquestion`
--
ALTER TABLE `studentquestion`
ADD CONSTRAINT `studentquestion_ibfk_1` FOREIGN KEY (`stdid`) REFERENCES `student` (`stdid`),
ADD CONSTRAINT `studentquestion_ibfk_2` FOREIGN KEY (`testid`, `qnid`) REFERENCES `question` (`testid`, `qnid`);
ERROR MESSAGE
Cannot delete or update a parent row: a foreign key constraint fails (oes.studentquestion, CONSTRAINT studentquestion_ibfk_2 FOREIGN KEY (testid, qnid) REFERENCES question (testid, qnid))
Perhaps it is not the full script you have.
Most probably the data is inserted in wrong order. The error occurs because the table studentquestion already has the data for the testid and qnid fields which is not present is the question master table. You have to reorder your insert-statements so that master tables are populated first and the detail tables after them.

The way foreign keys work when there are 3 tables dependent on each other

I have tables
items
products
brands
their contents:
products:
- samsung galaxy s2
- iphone 5
brands
- samsung
- apple
the difference between an item and a product is as follows:
product is lets say iPhone.
item is a certain user's certain iPhone with its own properties like color and purchase price.
the product iPhone has a brand/manufacturer of Apple.
when inserting a new item, I want the database to get the brand from the product the item belongs to, so my foreign key is set up like this:
'db_name`.'products'.`productBrand`
I have two brands ATM - Samsung and Apple.
When I try to insert a new item via phpMyAdmin's interface and I get to the itemBrand column, the dropdown field only allows me one option - 1 (Samsung), no matter if I've chosen product 1 or 2 (Samsung Galaxy or iPhone5) at the itemGenericProduct column.
What am I doing wrong?
Here is some more detailed info:
CREATE TABLE IF NOT EXISTS `brands` (
`brandId` int(11) NOT NULL AUTO_INCREMENT,
`brandName` varchar(30) NOT NULL,
`brandLogo` varchar(100) NOT NULL,
`brandDescription` text NOT NULL,
PRIMARY KEY (`brandId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `brands`
--
INSERT INTO `brands` (`brandId`, `brandName`, `brandLogo`, `brandDescription`) VALUES
(1, 'Samsung', '', 'Manufacturer of ...'),
(2, 'Apple', '', 'American high-tech company ...');
--
-- Table structure for table `items`
--
CREATE TABLE IF NOT EXISTS `items` (
`itemId` int(11) NOT NULL AUTO_INCREMENT,
`generalProductId` int(11) NOT NULL,
`itemPurchasedPrice` double NOT NULL,
`itemDateAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`itemDescription` text,
`itemBrand` int(11) NOT NULL,
`itemBoughtFromPlace` int(11) NOT NULL,
`itemBoughtFromUser` int(11) NOT NULL,
`itemConditionNew` tinyint(1) NOT NULL DEFAULT '1',
`itemBeingSold` tinyint(1) NOT NULL DEFAULT '1',
`itemSellPrice` double DEFAULT NULL,
PRIMARY KEY (`itemId`),
KEY `generalProductId` (`generalProductId`),
KEY `itemBrand` (`itemBrand`),
KEY `itemBoughtFromPlace` (`itemBoughtFromPlace`),
KEY `itemBoughtFromUser` (`itemBoughtFromUser`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- Table structure for table `products`
--
CREATE TABLE IF NOT EXISTS `products` (
`productId` int(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(200) NOT NULL,
`productTimeAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`productDescription` text,
`productBrand` int(11) NOT NULL,
`productFirstAddedFrom` int(11) NOT NULL,
`productAvatar` varchar(100) DEFAULT NULL,
PRIMARY KEY (`productId`),
KEY `productBrand` (`productBrand`,`productFirstAddedFrom`),
KEY `productFirstAddedFrom` (`productFirstAddedFrom`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`productId`, `productName`, `productTimeAdded`, `productDescription`, `productBrand`, `productFirstAddedFrom`, `productAvatar`) VALUES
(3, 'Samsung Galaxy SII', '2013-10-26 07:46:08', 'The Samsung Galaxy S II is a .....', 1, 1, NULL),
(4, 'iPhone 5', '2013-10-26 07:46:08', 'The iPhone 5 is a ....', 1, 2, NULL);
EDIT:
the following lines in PRODUCTS table seem strange
KEY `productBrand` (`productBrand`,`productFirstAddedFrom`),
KEY `productFirstAddedFrom` (`productFirstAddedFrom`)
because in the visual layout they look this way:
Foreign keys must point at a column of an other table (which has to be the same (ex.: INT(11) - INT(11)).
When your tables are created, you can add a foreign key by using
ALTER TABLE mytable ADD FOREIGN KEY (myfkey) REFERENCES myothertable(parentkey)
Now if we apply it to your structure:
DROP TABLE items; DROP TABLE brands; DROP TABLE products;
CREATE TABLE IF NOT EXISTS `brands` (
`brandId` int(11) NOT NULL AUTO_INCREMENT,
`brandName` varchar(30) NOT NULL,
`brandLogo` varchar(100) NOT NULL,
`brandDescription` text NOT NULL,
PRIMARY KEY (`brandId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
INSERT INTO `brands` (`brandId`, `brandName`, `brandLogo`, `brandDescription`) VALUES
(1, 'Samsung', '', 'Manufacturer of ...'),
(2, 'Apple', '', 'American high-tech company ...');
CREATE TABLE IF NOT EXISTS `items` (
`itemId` int(11) NOT NULL AUTO_INCREMENT,
`generalProductId` int(11) NOT NULL,
`itemPurchasedPrice` double NOT NULL,
`itemDateAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`itemDescription` text,
`itemBrand` int(11) NOT NULL,
`itemBoughtFromPlace` int(11) NOT NULL,
`itemBoughtFromUser` int(11) NOT NULL,
`itemConditionNew` tinyint(1) NOT NULL DEFAULT '1',
`itemBeingSold` tinyint(1) NOT NULL DEFAULT '1',
`itemSellPrice` double DEFAULT NULL,
PRIMARY KEY (`itemId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `products` (
`productId` int(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(200) NOT NULL,
`productTimeAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`productDescription` text,
`productBrand` int(11) NOT NULL,
`productFirstAddedFrom` int(11) NOT NULL,
`productAvatar` varchar(100) DEFAULT NULL,
PRIMARY KEY (`productId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `products` (`productId`, `productName`, `productTimeAdded`, `productDescription`, `productBrand`, `productFirstAddedFrom`, `productAvatar`) VALUES
(3, 'Samsung Galaxy SII', '2013-10-26 07:46:08', 'The Samsung Galaxy S II is a .....', 1, 1, NULL),
(4, 'iPhone 5', '2013-10-26 07:46:08', 'The iPhone 5 is a ....', 1, 2, NULL);
ALTER TABLE items ADD FOREIGN KEY(generalProductId) REFERENCES products(productId) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE products ADD FOREIGN KEY(productBrand) REFERENCES brands(brandId) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE items ADD FOREIGN KEY(itemBrand) REFERENCES product(productBrand) ON DELETE CASCADE ON UPDATE CASCADE;
If you want to keep the brandID stored in the items table, the foreign key constarint has to be a composite one (and a Unique index added to products in order for that to work):
Table brands:
CREATE TABLE IF NOT EXISTS `brands` (
`brandId` int(11) NOT NULL AUTO_INCREMENT,
`brandName` varchar(30) NOT NULL,
`brandLogo` varchar(100) NOT NULL,
`brandDescription` text NOT NULL,
PRIMARY KEY (`brandId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
INSERT INTO `brands` (`brandId`, `brandName`, `brandLogo`, `brandDescription`)
VALUES
(1, 'Samsung', '', 'Manufacturer of ...'),
(2, 'Apple', '', 'American high-tech company ...');
Table products:
CREATE TABLE IF NOT EXISTS `products` (
`productId` int(11) NOT NULL AUTO_INCREMENT,
`productName` varchar(200) NOT NULL,
`productTimeAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`productDescription` text,
`productBrand` int(11) NOT NULL,
`productFirstAddedFrom` int(11) NOT NULL,
`productAvatar` varchar(100) DEFAULT NULL,
PRIMARY KEY (`productId`),
KEY `productBrand` (`productBrand`,`productFirstAddedFrom`),
KEY `productFirstAddedFrom` (`productFirstAddedFrom`),
FOREIGN KEY (productBrand) -- FK added
REFERENCES brands (brandId),
UNIQUE (productBrand, productId) -- Unique index added
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
INSERT INTO `products`
(`productId`, `productName`, `productTimeAdded`, `productDescription`,
`productBrand`, `productFirstAddedFrom`, `productAvatar`)
VALUES
(3, 'Samsung Galaxy SII', '2013-10-26 07:46:08', 'The Samsung Galaxy S II is a .....', 1, 1, NULL),
(4, 'iPhone 5', '2013-10-26 07:46:08', 'The iPhone 5 is a ....', 1, 2, NULL);
Table items:
CREATE TABLE IF NOT EXISTS `items` (
`itemId` int(11) NOT NULL AUTO_INCREMENT,
`generalProductId` int(11) NOT NULL,
`itemPurchasedPrice` double NOT NULL,
`itemDateAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`itemDescription` text,
`itemBrand` int(11) NOT NULL,
`itemBoughtFromPlace` int(11) NOT NULL,
`itemBoughtFromUser` int(11) NOT NULL,
`itemConditionNew` tinyint(1) NOT NULL DEFAULT '1',
`itemBeingSold` tinyint(1) NOT NULL DEFAULT '1',
`itemSellPrice` double DEFAULT NULL,
PRIMARY KEY (`itemId`),
KEY `generalProductId` (`generalProductId`),
KEY `itemBrand` (`itemBrand`),
KEY `itemBoughtFromPlace` (`itemBoughtFromPlace`),
KEY `itemBoughtFromUser` (`itemBoughtFromUser`),
FOREIGN KEY (itemBrand, generalProductId) -- composite FK
REFERENCES products (productBrand, productId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

Update MySQL: Duplicate unique key #1062

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.