MySQL create table with condition on column - mysql

I want to create a customer table and want to restrict the SponsorID column not null if CustomerType=Guest.
CREATE TABLE `customers` (
`CustomerID` INT(11) NOT NULL AUTO_INCREMENT,
`CustomerType` VARCHAR(45) NOT NULL,
`WM_Status` TINYINT(1) NOT NULL,
`SponsorID` INT(11) NULL,
`F_Name` VARCHAR(45) NOT NULL,
`L_Name` VARCHAR(45) NOT NULL,
`Street` VARCHAR(80) NULL DEFAULT NULL,
`City` VARCHAR(45) NULL DEFAULT NULL,
`State` CHAR(4) NULL DEFAULT NULL,
`Zip` INT(11) NULL DEFAULT NULL,
`WorkNum` VARCHAR(45) NULL DEFAULT NULL,
`HomeNum` VARCHAR(45) NOT NULL,
`DOB` DATE NOT NULL,
PRIMARY KEY (`CustomerID`),
UNIQUE INDEX `CustomerID_UNIQUE` (`CustomerID` ASC) ,
INDEX `SponsorID` (`SponsorID` ASC) ,
CONSTRAINT `SponsorID`
FOREIGN KEY (`SponsorID`)
REFERENCES `project1_team3`.`customers` (`CustomerID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
Please suggest.
Any help would be appreciated.
Thanks,

You could add a constraint like this one.
CONSTRAINT SponsorIDCheck CHECK ((`CustomerType` != 'Guest') OR (`CustomerType` = 'Guest' AND `SponsorID` IS NOT NULL))

Related

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

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

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.