Mysql error 1215 - Cannot add foreign key constraint - mysql

Created these two tables successfully
First table
CREATE TABLE IF NOT EXISTS `lawncare_user` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
`Email` varchar(255) NOT NULL,
`UserType` varchar(30) NOT NULL,
`UserName` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
`ModifiedOn` date DEFAULT NULL,
`Status` BOOLEAN NOT NULL DEFAULT '0',
`QuestionID` int(11) DEFAULT NULL,
`QuestionAnswer` text DEFAULT NULL,
`Params` text NOT NULL,
`Address` text NOT NULL,
`Country` varchar(300) NOT NULL,
`State` varchar(300) NOT NULL,
`City` varchar(300) NOT NULL,
`ContactNo` double DEFAULT NULL,
`Activation` BOOLEAN NOT NULL DEFAULT '0',
`ActivatedOn` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Second table
CREATE TABLE IF NOT EXISTS `lawncare_customer` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
`Email` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`ContactNo` varchar(20) NOT NULL,
`Address` varchar(255) NOT NULL,
`Params` text NOT NULL,
`Province` varchar(255) NOT NULL,
`ZipCode` varchar(255) NOT NULL,
`Status` Boolean NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
`ModifiedOn` date DEFAULT NULL
) ENGINE =InnoDB DEFAULT CHARSET=latin1;
But while creating third table as
CREATE TABLE IF NOT EXISTS `lawncare_message` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`Reason` int(5) NOT NULL,
`Subject` text NOT NULL,
`Description` text NOT NULL,
`Customer` int(11) NOT NULL,
`CustomerUser` varchar(255) NOT NULL,
`CustomerEmail` varchar(255) NOT NULL,
`SendTo` int(11) NOT NULL,
`SendToUser` varchar(255) NOT NULL,
`SendToEmail` varchar(255) NOT NULL,
`Status` int(5) NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL
FOREIGN KEY (SendTo, SendToUser, SendToEmail)
REFERENCES lawncare_user(ID, UserName, Email)
ON UPDATE CASCADE ,
FOREIGN KEY (Customer, CustomerUser, CustomerEmail)
REFERENCES lawncare_customer(ID, FirstName,Email)
ON UPDATE CASCADE
) ENGINE =InnoDB DEFAULT CHARSET=latin1
I get #1215 - Cannot add foreign key constraint , error in mysql tried adding foreign keys after creating table but it still gives the same error. I don't know what I'm doing wrong here.

First of all Check whether you have applied indexes on the keys.
As per your code their is no point in referencing id,UserName and Email.
Only id is enough for referencing.
Check the following code
CREATE TABLE IF NOT EXISTS `lawncare_message` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`Reason` int(5) NOT NULL,
`Subject` text NOT NULL,
`Description` text NOT NULL,
`Customer` int(11) NOT NULL,
`CustomerUser` varchar(255) NOT NULL,
`CustomerEmail` varchar(255) NOT NULL,
`SendTo` int(11) NOT NULL,
`SendToUser` varchar(255) NOT NULL,
`SendToEmail` varchar(255) NOT NULL,
`Status` int(5) NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
FOREIGN KEY (SendTo)
REFERENCES lawncare_user(ID)
ON UPDATE CASCADE ,
FOREIGN KEY (Customer)
REFERENCES lawncare_customer(ID)
ON UPDATE CASCADE
) ENGINE =InnoDB DEFAULT CHARSET=latin1

Related

MY-SQL table query giving incorrect result until i optimize the table

I have this table:
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`origin_post_id` int(11) NOT NULL,
`ref_post_id` int(11) NOT NULL,
`broker_user_id` int(11) NOT NULL,
`isshared` tinyint(4) NOT NULL,
`type` tinyint(4) NOT NULL,
`deal_type` tinyint(4) NOT NULL,
`title` varchar(200) NOT NULL,
`currency` varchar(10) NOT NULL,
`country_code` varchar(10) NOT NULL,
`price` float(10,2) NOT NULL,
`price_to` float(10,2) NOT NULL,
`sector` int(11) NOT NULL,
`protype` int(11) NOT NULL,
`sea_view` int(11) NOT NULL,
`sea_view_to` int(11) NOT NULL,
`area` int(11) NOT NULL,
`area_to` int(11) NOT NULL,
`area_mesure_type` tinyint(4) NOT NULL DEFAULT '1',
`building_area` int(11) NOT NULL,
`building_area_to` int(11) NOT NULL,
`building_area_mesure_type` tinyint(4) NOT NULL DEFAULT '1',
`bathrooms` int(11) NOT NULL,
`bathrooms_to` int(11) NOT NULL,
`rooms` int(11) NOT NULL,
`rooms_to` int(11) NOT NULL,
`location` varchar(300) NOT NULL,
`lat` float NOT NULL,
`lng` float NOT NULL,
`description` text NOT NULL,
`map_data` varchar(500) NOT NULL,
`shape_data` text NOT NULL,
`seo_title` varchar(300) NOT NULL,
`seo_keywords` varchar(300) NOT NULL,
`seo_description` varchar(300) NOT NULL,
`status` tinyint(4) NOT NULL,
`publish_date` date NOT NULL,
`expiry_date` date NOT NULL,
`request_status` enum('','NEW','ACCEPTED','REJECTED') NOT NULL,
`request_date` date NOT NULL,
`accept_date` date NOT NULL,
`share_per` float(5,2) NOT NULL,
`deal_completed` tinyint(4) NOT NULL,
`completed_by` int(11) NOT NULL,
`created` datetime NOT NULL,
`updated` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `type` (`type`),
KEY `deal_type` (`deal_type`),
KEY `price` (`price`),
KEY `sector` (`sector`),
KEY `protype` (`protype`),
KEY `sea_view` (`sea_view`),
KEY `area` (`area`),
KEY `building_area` (`building_area`),
KEY `bathrooms` (`bathrooms`),
KEY `rooms` (`rooms`),
KEY `lat` (`lat`),
KEY `lng` (`lng`),
KEY `status` (`status`),
KEY `price_to` (`price_to`),
KEY `sea_view_to` (`sea_view_to`),
KEY `area_to` (`area_to`),
KEY `building_area_to` (`building_area_to`),
KEY `bathrooms_to` (`bathrooms_to`),
KEY `rooms_to` (`rooms_to`),
KEY `request_status` (`request_status`),
KEY `request_date` (`request_date`),
KEY `accept_date` (`accept_date`),
KEY `ref_post_id` (`ref_post_id`),
KEY `deal_completed` (`deal_completed`),
KEY `location` (`location`(255)),
KEY `user_id` (`user_id`),
KEY `country_code` (`country_code`),
KEY `expiry_date` (`expiry_date`),
KEY `origin_post_id` (`origin_post_id`),
KEY `completed_by` (`completed_by`),
FULLTEXT KEY `title_location_description` (`title`,`location`,`description`),
CONSTRAINT `posts_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `app_users` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=833 DEFAULT CHARSET=utf8
When I run select count(id) from posts where deal_completed='1' and user_id='<anyuserid>' then it gives zero records always but when I optimize this table then it's giving correct result and after some time I need again to optimize the table.
May be it is because of too many key you are using. Key should only be used if you are going to search table using that column or order by that column which makes operation fast. If not required do not use too many keys, as you have optimize the table again and again. Try to normalize the table as much you can and try to use FOREIGN KEYS. And as #Tim said if it is an int try int.

Foreign key won't add

I have these two tables but the foreign key won't add. This is the query I'm using but I keep getting cannot add foreign key error. I have also included the Create table statements. Thanks for any help
ALTER TABLE courses ADD CONSTRAINT fk_fs FOREIGN KEY (teacher1)
REFERENCES teachers(fullName)
CREATE TABLE IF NOT EXISTS `courses` (
`courseID` int(11) NOT NULL AUTO_INCREMENT,
`courseName` varchar(200) DEFAULT NULL,
`module1` varchar(200) DEFAULT NULL,
`module2` varchar(200) DEFAULT NULL,
`module3` varchar(200) DEFAULT NULL,
`module4` varchar(200) DEFAULT NULL,
`teacher1` varchar(200) DEFAULT NULL,
`teacher2` varchar(200) DEFAULT NULL,
`teacher3` varchar(200) DEFAULT NULL,
`teacher4` varchar(200) DEFAULT NULL,
PRIMARY KEY (`courseID`)
)
CREATE TABLE IF NOT EXISTS `teachers` (
`teacherID` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(11) DEFAULT NULL,
`fullName` varchar(200) DEFAULT NULL,
`officeOpen` varchar(5) DEFAULT NULL,
`officeClose` varchar(5) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
PRIMARY KEY (`teacherID`)
)
Foreign keys in MySQL must reference indexed columns. I think what you really want to do is add a foreigh-key column to the "courses" table, ex. fkTeacherID column as follows:
CREATE TABLE IF NOT EXISTS `courses` (
`courseID` int(11) NOT NULL AUTO_INCREMENT,
`courseName` varchar(200) DEFAULT NULL,
`module1` varchar(200) DEFAULT NULL,
`module2` varchar(200) DEFAULT NULL,
`module3` varchar(200) DEFAULT NULL,
`module4` varchar(200) DEFAULT NULL,
`teacher1` varchar(200) DEFAULT NULL,
`teacher2` varchar(200) DEFAULT NULL,
`teacher3` varchar(200) DEFAULT NULL,
`teacher4` varchar(200) DEFAULT NULL,
`fkTeacherID` int(11),
PRIMARY KEY (`courseID`)
);
CREATE TABLE IF NOT EXISTS `teachers` (
`teacherID` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(11) DEFAULT NULL,
`fullName` varchar(200) DEFAULT NULL,
`officeOpen` varchar(5) DEFAULT NULL,
`officeClose` varchar(5) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
PRIMARY KEY (`teacherID`)
);
ALTER TABLE courses ADD CONSTRAINT fk_fs FOREIGN KEY (fkTeacherID)
REFERENCES teachers(TeacherID)
You can then create a query like:
SELECT fullName
from teachers t
inner join courses c on t.TeacherID = c.fkTeacherID
You can then eliminate the teacher1..4 columns. You may also want to the same with modules. You also eliminate the 4 teachers to a course constraint.
SQLFIDDLE

Not able to create a Foreign Constraint in Mysql

Here is the script I am trying to run
CREATE TABLE IF NOT EXISTS `store` (
`store_id` INT NOT NULL AUTO_INCREMENT,
`store_name` VARCHAR(1024) NOT NULL,
`store_user` INT NOT NULL,
`store_address` INT NOT NULL,
`store_type` INT NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`store_id`)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `store_address` (
`address_id` INT NOT NULL AUTO_INCREMENT,
`address_line_1` VARCHAR(1024) NOT NULL,
`address_line_2` VARCHAR(1024) NOT NULL,
`address_line_3` VARCHAR(1024) NULL,
`city` VARCHAR(45) NOT NULL,
`locality` VARCHAR(100) NOT NULL,
`pincode` CHAR(6) NOT NULL,
`latitude` DECIMAL(8,6) NULL,
`longitude` DECIMAL(9,6) NULL,
`state` VARCHAR(45) NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`address_id`),
CONSTRAINT `FK_STR_STR_ADR`
FOREIGN KEY (`address_id`)
REFERENCES `store` (`store_address`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I get this error - Error Code: 1215. Cannot add foreign key constraint
No clue what is wrong with the DDL
Two issues:
1. use unsigned int for the primary keys (Edit: this is a good idea but was not the problem)
2. the store.store address must be a key in the store table in order to use it in a foreign key constraint in the store_address table
CREATE TABLE IF NOT EXISTS `store` (
`store_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`store_name` VARCHAR(1024) NOT NULL,
`store_user` INT NOT NULL,
`store_address` int(10) unsigned NOT NULL DEFAULT 0,
`store_type` INT NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`store_id`),
KEY (`store_address`)
) ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `store_address` (
`address_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`address_line_1` VARCHAR(1024) NOT NULL,
`address_line_2` VARCHAR(1024) NOT NULL,
`address_line_3` VARCHAR(1024) NULL,
`city` VARCHAR(45) NOT NULL,
`locality` VARCHAR(100) NOT NULL,
`pincode` CHAR(6) NOT NULL,
`latitude` DECIMAL(8,6) NULL,
`longitude` DECIMAL(9,6) NULL,
`state` VARCHAR(45) NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`address_id`),
CONSTRAINT `FK_STR_STR_ADR` FOREIGN KEY (`address_id`) REFERENCES `store` (`store_address`)
)ENGINE = InnoDB;

How to optimize a MySQL JOIN Query

I have this MySQL query that I want to optimize:
SELECT r.WarehouseLocation,sum(sir.qty)
FROM repairableissue as r
INNER JOIN SIR ON r.sirno=sir.sirno
AND r.region=sir.region
AND r.ItemName=sir.Itemdesc
AND r.SerialNo=sir.Serialno
WHERE r.status='Pending'
GROUP BY r.warehouseLocation
How do I optimize this query? I read about optimization and found out that indexes might help but still could not achieve the desired performance.
Which index should be used and which should be removed?
Below is the explain of query:
Repairableissue
CREATE TABLE `repairableissue` (
`Vendor` varchar(40) NOT NULL,
`ItemName` varchar(200) NOT NULL,
`SerialNo` varchar(50) NOT NULL,
`person` varchar(200) NOT NULL,
`siteid` varchar(10) NOT NULL,
`invuser` varchar(50) NOT NULL,
`region` varchar(50) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`Dated` date NOT NULL,
`Sirno` varchar(50) NOT NULL,
`status` varchar(30) NOT NULL DEFAULT 'Pending',
`trackthrough` varchar(30) NOT NULL,
`reason` varchar(100) NOT NULL,
`ckh` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`WarehouseType` varchar(20) NOT NULL,
`WarehouseLocation` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `I1` (`status`),
KEY `ind2` (`ItemName`),
KEY `ind3` (`region`),
KEY `ind5` (`SerialNo`),
KEY `ind4` (`Sirno`)
) ENGINE=MyISAM AUTO_INCREMENT=63029 DEFAULT CHARSET=latin1
sir
CREATE TABLE `sir` (
`SirNo` varchar(50) NOT NULL,
`SiteId` varchar(80) NOT NULL,
`Vendor` varchar(70) NOT NULL,
`Type` varchar(15) NOT NULL,
`ItemDesc` varchar(200) NOT NULL,
`ItemCode` varchar(25) NOT NULL,
`SerialNo` varchar(50) NOT NULL,
`Unit` varchar(15) NOT NULL,
`AssetCode` varchar(50) NOT NULL,
`Qty` decimal(11,0) NOT NULL,
`Region` varchar(15) NOT NULL,
`Status` varchar(20) NOT NULL DEFAULT 'Installed',
`FaultInfo` varchar(100) NOT NULL DEFAULT 'date()',
`chk` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Phase` varchar(15) NOT NULL,
`Category` varchar(200) NOT NULL,
`Issue_Vendor` varchar(30) NOT NULL,
`AssetName` varchar(150) NOT NULL,
`Ownership` varchar(20) NOT NULL,
`Dated` date NOT NULL,
`PersonName` varchar(150) NOT NULL,
`Remarks` varchar(300) NOT NULL,
`po` varchar(100) NOT NULL,
`invuser` varchar(50) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`grnno` varchar(30) NOT NULL,
`WarehouseType` varchar(20) NOT NULL,
`WarehouseLocation` varchar(20) NOT NULL,
`mainpartserial` varchar(200) NOT NULL,
PRIMARY KEY (`Vendor`,`Type`,`ItemCode`,`ItemDesc`,`SerialNo`,`Ownership`,`SirNo`,`Region`,`WarehouseType`,`WarehouseLocation`,`po`,`Qty`,`id`),
KEY `id` (`id`),
KEY `ind4` (`ItemDesc`),
KEY `ind6` (`SerialNo`),
KEY `ind7` (`SerialNo`)
) ENGINE=MyISAM AUTO_INCREMENT=228007 DEFAULT CHARSET=latin1
One multi-column index on r.status + r.warehouseLocation, in that order.
One multi-column index on sir.sirno + sir.region + sir.Itemdesc + sir.Serialno, in order of most cardinality to least cardinality, with sir.qty tacked on the end.
This assumes the fields are small enough to fit (combined) into an index.
Still, join seeks are unavoidable. The number of records that match r.status='Pending' is going to dictate the speed of this query.

How to check if a given data exists in onther table MySql?

I have two tables in MySql Database:
Captain(captain.email)
Members(member.email)
I want when captain table insert data in captain.email then check If members table data in members.email are already exit then data in captain.email not insert in captain table.
How it is possible ?
1.Captain :
CREATE TABLE `captain` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`username_canonical` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`email_canonical` varchar(255) NOT NULL,
`enabled` tinyint(1) NOT NULL,
`salt` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`last_login` datetime DEFAULT NULL,
`locked` tinyint(1) NOT NULL,
`expired` tinyint(1) NOT NULL,
`expires_at` datetime DEFAULT NULL,
`confirmation_token` varchar(255) DEFAULT NULL,
`password_requested_at` datetime DEFAULT NULL,
`roles` longtext NOT NULL COMMENT '(DC2Type:array)',
`credentials_expired` tinyint(1) NOT NULL,
`credentials_expire_at` datetime DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQ_957A647992FC23A8` (`username_canonical`),
UNIQUE KEY `UNIQ_957A6479A0D96FBF` (`email_canonical`)
)
2.Members :
CREATE TABLE `members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`team_id` int(11) DEFAULT NULL,
`fos_user_id` int(11) DEFAULT NULL,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`mobile` varchar(45) DEFAULT NULL,
`role` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `email_2` (`email`),
KEY `IDX_45A0D2FF296CD8AE` (`team_id`),
KEY `IDX_45A0D2FF8C20A0FB` (`fos_user_id`),
CONSTRAINT `FK_45A0D2FF296CD8AE` FOREIGN KEY (`team_id`) REFERENCES `team` (`id`),
CONSTRAINT `FK_45A0D2FF8C20A0FB` FOREIGN KEY (`fos_user_id`) REFERENCES `fos_user` (`id`)
)
There is no way to enforce such constraint.
Using declarative referential integrity (DRI) you could create a table that contains all of the columns that you need to build a unique key on.