Not able to create a Foreign Constraint in Mysql - 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;

Related

customers table wont allow constraint

Hey so im trying to load in my database. The error I get is
CREATE TABLE `customers` (
`customerNumber` int(11) NOT NULL,
`customerName` varchar(50) NOT NULL,
`contactLastName` varchar(50) NOT NULL,
`contactFirstName` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`city` varchar(50) NOT NULL,
`state` varchar(50) DEFAULT NULL,
`postalCode` varchar(15) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`salesRepEmployeeNumber` int(11) DEFAULT NULL,
`creditLimit` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`customerNumber`),
KEY `salesRepEmployeeNumber` (`salesRepEmployeeNumber`),
CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`salesRepEmployeeNumber`) REFERENCES `employees` (`employeeNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
MySQL said: Documentation
1215 - Cannot add foreign key constraint
I understand the error but whats the problem its having with the constraint?
Edit:
0
CREATE TABLE `employees` (
`employeeNumber` int(11) NOT NULL,
`lastName` varchar(50) NOT NULL,
`firstName` varchar(50) NOT NULL,
`extension` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
`officeCode` varchar(10) NOT NULL,
`reportsTo` int(11) DEFAULT NULL,
`jobTitle` varchar(50) NOT NULL,
PRIMARY KEY (`employeeNumber`),
KEY `reportsTo` (`reportsTo`),
KEY `officeCode` (`officeCode`),
CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`reportsTo`) REFERENCES `employees` (`employeeNumber`),
CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES `offices` (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `offices` (
`officeCode` varchar(10) NOT NULL,
`city` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`state` varchar(50) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`postalCode` varchar(15) NOT NULL,
`territory` varchar(10) NOT NULL,
PRIMARY KEY (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Ok, you should create the tables in this order:
1.- Your table offices
2.- Your table employees
3.- Your table customers.
The problem is that you are trying to create first the table customers, and it ´s refering a table (employees) that does not exist.

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.

Mysql error 1215 - Cannot add foreign key constraint

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

error 105 mysql FOREIGN KEYS

I am trying to create database table and get them connected by mysql FOREIGN KEYS. I have ensured that my data types are identical. I also ensure that my tables are made before added the FK. Any advice would be greatly appreciated.
CREATE TABLE IF NOT EXISTS `af_feeds` (
`id` int(64) unsigned NOT NULL AUTO_INCREMENT,
`hash` char(255) NOT NULL,
`seed_id` int(64) NOT NULL,
`category_id` int(64) NOT NULL,
`title` varchar(255) NOT NULL,
`description` text,
`content` longtext,
`publishing_date` varchar(255) NOT NULL,
`link` text NOT NULL,
`status` int(1) NOT NULL,
`create_date` int(64) NOT NULL,
`update_date` int(64) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `hash` (`hash`),
FOREIGN KEY (`seed_id`) REFERENCES `af_seeds`(`id`)
ON UPDATE CASCADE
ON DELETE CASCADE,
FOREIGN KEY (`category_id`) REFERENCES `af_categories`(`id`)
ON UPDATE CASCADE
ON DELETE CASCADE
MySQL said:
1005 - Can't create table 'estafeed_rss.af_feeds' (errno: 150) (Details…)
--
-- Table structure for table `af_categories`
--
CREATE TABLE IF NOT EXISTS `af_categories` (
`id` int(64) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`icon` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`status` int(1) NOT NULL,
`create_date` int(64) NOT NULL,
`update_date` int(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
-- --------------------------------------------------------
--
-- Table structure for table `af_seeds`
--
CREATE TABLE IF NOT EXISTS `af_seeds` (
`id` int(64) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`link` varchar(255) NOT NULL,
`category_id` int(64) NOT NULL,
`loading_times` int(64) NOT NULL,
`status` int(1) NOT NULL,
`loading_each` int(64) NOT NULL,
`last_loading` int(64) NOT NULL,
`create_date` int(64) NOT NULL,
`update_date` int(64) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `url` (`link`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;

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.