I have tabel users:
CREATE TABLE IF NOT EXISTS `ePrzychodnia`.`users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`firstName` VARCHAR(45) NOT NULL ,
`lastName` VARCHAR(45) NOT NULL ,
`personalId` VARCHAR(11) NOT NULL ,
`password` VARCHAR(45) NOT NULL ,
`city` VARCHAR(45) NULL ,
`address` VARCHAR(45) NULL ,
`email` VARCHAR(45) NULL ,
`phone` VARCHAR(45) NULL ,
`specialization` VARCHAR(45) NULL ,
`role` VARCHAR(45) NOT NULL ,
`active` TINYINT(1) NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `personalId_UNIQUE` (`personalId` ASC) )
and tabel visits. Tabel visits have two foreign key to the users table
CREATE TABLE IF NOT EXISTS `ePrzychodnia`.`visits` (
`id` INT NULL AUTO_INCREMENT ,
`doctorId` INT NOT NULL ,
`patientId` INT NULL,
`dateVisit` DATE NOT NULL ,
`hourVisit` DATE NOT NULL ,
PRIMARY KEY (`id`, `doctorId`, `patientId`) ,
INDEX `fk_visits_Users1_idx` (`doctorId` ASC) ,
INDEX `fk_visits_Users2_idx` (`patientId` ASC) ,
CONSTRAINT `fk_visits_Users1`
FOREIGN KEY (`doctorId` )
REFERENCES `ePrzychodnia`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_visits_Users2`
FOREIGN KEY (`patientId` )
REFERENCES `ePrzychodnia`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
The second foreign key I set that can be null, because I care about adding an entry to the table visits where it will be empty.
However, when you try to add I get an error
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (eprzychodnia.visits, CONSTRAINT fk_visits_Users2 FOREIGN KEY (patientId) REFERENCES users (id) ON DELETE NO ACTION ON UPDATE NO ACTION)
What can I do to make the key could be null?
In your relation setup change the action on update and delete
The problem is not your foreign key, it's your primary key. You can't have nullable fields in a primary key. The id field by itself might be a better choice.
I'm not a fan of nullable foreign keys. I would add a record to your users table that equates to "not an actual person" and use it as a default. By the way, the hourvisit field might be redundant.
Dana Bruck I do not know if I understand your proposals. But it seems to me that it's something like this:
Table visits
CREATE TABLE IF NOT EXISTS `ePrzychodnia`.`visits` (
`id` INT NULL AUTO_INCREMENT ,
`doctorId` INT NOT NULL ,
`patientId` INT NULL,
`dateVisit` DATE NOT NULL ,
`hourVisit` DATE NOT NULL ,
PRIMARY KEY (`id`, `doctorId`, `patientId`))
Table without foreign keys. The fields not related to the table users, but I set these fields when I need and this field may be null.
If the id in visits is auto_increment, why you create your PK with 3 columns ??
Just id is enough. You can create a unique index for doctor and patience ID.
Try this model:
CREATE TABLE IF NOT EXISTS `ePrzychodnia`.`visits` (
`id` INT NOT NULL AUTO_INCREMENT ,
`doctorId` INT NOT NULL ,
`patientId` INT NULL,
`dateVisit` DATE NOT NULL ,
`hourVisit` DATE NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `unique_doctor_pacient` (`doctorId`, `patientId`),
INDEX `fk_visits_Users1_idx` (`doctorId` ASC) ,
INDEX `fk_visits_Users2_idx` (`patientId` ASC) ,
CONSTRAINT `fk_visits_Users1`
FOREIGN KEY (`doctorId` )
REFERENCES `ePrzychodnia`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_visits_Users2`
FOREIGN KEY (`patientId` )
REFERENCES `ePrzychodnia`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
Related
I tried to create 2 foreign keys in customerdetails table but it keeps me showing an error when I execute this query. Is there any problem with my query?
CREATE TABLE `vg_shippingdb`.`customerdetails` (
`CustomerID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(25) NOT NULL ,
`Age` INT NOT NULL ,
`Sex` VARCHAR(10) NOT NULL ,
`Email` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`CustomerID`),
FOREIGN KEY (ReservedID) REFERENCES reservationdetails(ReservedID),
FOREIGN KEY (TicketID) REFERENCES ticket(TicketID)) ENGINE = InnoDB;
CREATE TABLE `vg_shippingdb`.`reservationdetails` (
`ReservedID` INT NOT NULL AUTO_INCREMENT ,
`ReservedDate` DATE NOT NULL ,
`DepartureTime` VARCHAR(25) NOT NULL ,
`Destination` VARCHAR(45) NOT NULL ,
`Accommodation` TEXT NULL ,
`NameOfVessel` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`ReservedID`)) ENGINE = InnoDB;
CREATE TABLE `vg_shippingdb`.`ticket` (
`TicketID` INT NOT NULL AUTO_INCREMENT ,
`TicketNo` VARCHAR(25) NOT NULL ,
`Status` VARCHAR(25) NOT NULL ,
PRIMARY KEY (`TicketID`)) ENGINE = InnoDB;
The columns does not exist in a table really. Specifying the foreign key does not create a column, you must do it explicitly before the FK definition.
CREATE TABLE `vg_shippingdb`.`customerdetails` (
`CustomerID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(25) NOT NULL ,
`Age` INT NOT NULL ,
`Sex` VARCHAR(10) NOT NULL ,
`Email` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`CustomerID`),
-- Create columns
ReservedID INT,
TicketID INT,
-- Then use them in FK expressions
FOREIGN KEY (ReservedID) REFERENCES reservationdetails(ReservedID),
FOREIGN KEY (TicketID) REFERENCES ticket(TicketID)) ENGINE = InnoDB;
PS. The table which FK is refferred on must be created firstly - FK cannot refer the table which will be created later.
before creating foreign keys, create all tables
First create reservationdetails and ticket then create customerdetails.
Note: First create source/referred table then create table with FOREIGN KEY
Could you please help me figure this out
When I'm trying to create the table dvdTitle I'm getting below error
Error Code: 1005
Can't create table 'netflixclone.dvdtitle' (errno: 150)
Here is the code. Not sure what's going wrong
CREATE TABLE IF NOT EXISTS `netflixclone`.`person` (
`personID` INT NOT NULL ,
`personFirstName` VARCHAR(50) NULL ,
`personLastName` VARCHAR(50) NULL ,
`actor` TINYINT(1) NULL ,
`producer` TINYINT(1) NULL ,
`director` TINYINT(1) NULL ,
PRIMARY KEY (`personID`) );
CREATE TABLE IF NOT EXISTS `netflixclone`.`dvdTitle` (
`dvdID` INT NOT NULL AUTO_INCREMENT ,
`dvdMPPARating` VARCHAR(45) NULL ,
`dvdProducer` INT NOT NULL,
`dvdDirector` INT NOT NULL,
PRIMARY KEY (`dvdID`) ,
CONSTRAINT `personID`
FOREIGN KEY (`dvdProducer` , `dvdDirector` )
REFERENCES `netflixclone`.`person` (`personID` , `personID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION);
Try to create the 'netflixclone.dvdtitle' table with default charset as utf8.
CREATE TABLE IF NOT EXISTS `netflixclone`.`dvdTitle` (
`dvdID` INT NOT NULL AUTO_INCREMENT ,
`dvdMPPARating` VARCHAR(45) NULL ,
`dvdProducer` INT NOT NULL,
`dvdDirector` INT NOT NULL,
PRIMARY KEY (`dvdID`) ,
CONSTRAINT `personID`
FOREIGN KEY (`dvdProducer` , `dvdDirector` )
REFERENCES `netflixclone`.`person` (`personID` , `personID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION) CHARSET=utf8;
Your constraint is weird. I think you want two constraints here.
CREATE TABLE IF NOT EXISTS `netflixclone`.`dvdTitle` (
`dvdID` INT NOT NULL AUTO_INCREMENT ,
`dvdMPPARating` VARCHAR(45) NULL ,
`dvdProducer` INT NOT NULL,
`dvdDirector` INT NOT NULL,
PRIMARY KEY (`dvdID`) ,
CONSTRAINT FOREIGN KEY (`dvdProducer`) REFERENCES `netflixclone`.`person`
ON DELETE NO ACTION ON UPDATE NO ACTION),
CONSTRAINT FOREIGN KEY (`dvdDirector`) REFERENCES `netflixclone`.`person`
ON DELETE NO ACTION ON UPDATE NO ACTION)
);
FOREIGN KEY (dvdProducer)
REFERENCES netflixclone.person (personID )
you can try this
I searched through the prior posts but didn't quite find the answer, so here it goes ...
I have this table
CREATE TABLE `leags`
(
`lid` int(10) NOT NULL AUTO_INCREMENT,
`lName` varchar(255) NOT NULL,
`description` varchar(255) DEFAULT NULL,
`links` varchar(255) DEFAULT NULL,
`cid` int(10) NOT NULL,
PRIMARY KEY (`lid`),
KEY `index2` (`lid`,`lName`),
KEY `index3` (`lid`,`lName`,`cid`),
KEY `cid_idx` (`cid`),
CONSTRAINT `cid` FOREIGN KEY (`cid`) REFERENCES `cats` (`cid`)
)
ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Leagues'$$
I have another table that has the above PK as a foreign key.
CREATE TABLE `tams`
(
`tId` INT(10) NOT NULL ,
`tName` VARCHAR(255) NOT NULL ,
`lid` INT(10) NULL ,
`url` TEXT NULL ,
PRIMARY KEY (`tId`) ,
INDEX `index2` (`tId` ASC, `tName` ASC) ,
INDEX `index3` (`tId` ASC, `tName` ASC, `lid` ASC) ,
INDEX `lid_idx` (`lid` ASC) ,
CONSTRAINT `lid`
FOREIGN KEY (`lid` )
REFERENCES leags` (`lid` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
The creation of this table works fine, but I run into a problem creating the below table.
CREATE TABLE IF NOT EXISTS spSched
(
`spscId` INT(10) NOT NULL AUTO_INCREMENT ,
`startDate` DATE NOT NULL ,
`endDate` DATE NULL ,
`startTime` TIME NOT NULL ,
`endTime` TIME NULL ,
`htId` INT(10) NULL ,
`type` VARCHAR(45) NULL ,
`atId` INT(10) NULL ,
`leagId` INT(10) NULL ,
PRIMARY KEY (`spscId`) ,
UNIQUE INDEX `spscId_UNIQUE` (`spscId` ASC) ,
INDEX `htId_idx` (`htId` ASC) ,
INDEX `atId_idx` (`atId` ASC) ,
INDEX `lid_idx` (`leagId` ASC) ,
CONSTRAINT `tId`
FOREIGN KEY (`htId` )
REFERENCES tams (`tId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `atId`
FOREIGN KEY (`atId` )
REFERENCES tams` (`tId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `lId`
FOREIGN KEY (`leagId` )
REFERENCES leags (`lid` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
If I remove the lId as a FK and the constraint from the above sql, the table creates just fine. I can't figure out where the duplicate key is in here. All help is much appreciated.
Thanks.
lId you already have a constraint with this name in table tams lid.
I suspect your system is not case sensitive.
http://richardfearn.wordpress.com/2007/03/12/case-insensitive-constraint-names-in-mysql/
internally, InnoDB stores foreign key constraint names as
case-insensitive, with the database name prepended. So although
onedatabase.b_ibfk_1 is treated as different to
anotherdatabase.b_ibfk_1, Photos.b_ibfk_1 and photos.b_ibfk_1 are
treated as the same.
Just pick another name for that key.
Hi I have designed a database in mysql workbench. When I went to forward engineer I got (errno: 121) because I had foreign keys named the same in multiple tables which I realized is not allowed. I have quite a few junction tables as mostly n:m relationships. I am using composite primary keys (made up of 2 foreign keys) for most of these junction tables. My question is do I have to rename these primary keys to be unique along with the foreign keys?
Appreciate some help please.
(I have not renamed the foreign keys yet in below code)
CREATE TABLE IF NOT EXISTS `mydb`.`tblStudent` (
`StudentID` INT(6) NOT NULL AUTO_INCREMENT ,
`Student_Firstname` VARCHAR(20) NOT NULL ,
`Student_Lastname` VARCHAR(20) NOT NULL ,
`DOB` DATE NOT NULL ,
`Student_Gender` ENUM('Male','Female') NOT NULL ,
`Student_Address1` VARCHAR(40) NOT NULL ,
`Student_Address2` VARCHAR(22) NOT NULL ,
`Student_Address3` VARCHAR(14) NOT NULL ,
`Student_Phonenum` INT(10) NULL ,
`Student_Email` VARCHAR(60) NOT NULL ,
`Student_Password` CHAR(128) NOT NULL ,
`Enrollment_Date` DATE NOT NULL ,
`Graduation_Date` DATE NULL ,
`Student_Picture` VARCHAR(100) NOT NULL ,
`PPSN` VARCHAR(9) NOT NULL ,
PRIMARY KEY (`StudentID`) )
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `mydb`.`tblIllness` (
`IllnessID` CHAR(5) NOT NULL ,
`Illness_Name` VARCHAR(30) NOT NULL ,
PRIMARY KEY (`IllnessID`) )
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `mydb`.`tblStudentIllness` (
`IllnessID` CHAR(5) NOT NULL ,
`StudentID` INT(6) NOT NULL ,
`Doctor_Name` VARCHAR(30) NOT NULL ,
`Doctor_Phonenum` INT(10) NOT NULL ,
`Medication` VARCHAR(40) NOT NULL ,
`Medical_Advice` VARCHAR(250) NOT NULL ,
PRIMARY KEY (`IllnessID`, `StudentID`) ,
INDEX `IllnessID_idx` (`IllnessID` ASC) ,
INDEX `StudentID_idx` (`StudentID` ASC) ,
CONSTRAINT `IllnessID`
FOREIGN KEY (`IllnessID` )
REFERENCES `mydb`.`tblIllness` (`IllnessID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `StudentID`
FOREIGN KEY (`StudentID` )
REFERENCES `mydb`.`tblStudent` (`StudentID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
This compiles fine for me. One solution is to just remove the constraint names and they will be generated automatically for you.
...
CONSTRAINT
FOREIGN KEY (`IllnessID` )
REFERENCES `tblIllness` (`IllnessID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT
FOREIGN KEY (`StudentID` )
REFERENCES `tblStudent` (`StudentID` )
ON DELETE CASCADE
...
I'm modeling my db shema using MySQL Workbench CE EER modeler and now I'm stuck with mysql errno 150.
My sql code:
CREATE TABLE `myschema`.`Clients` (
`phone` VARCHAR(15) NOT NULL ,
`surname` VARCHAR(30) NOT NULL ,
`name` VARCHAR(30) NOT NULL ,
`middleName` VARCHAR(30) NULL ,
`discountCardNumber` BIGINT NULL ,
PRIMARY KEY (`phone`) ,
UNIQUE INDEX `discountCardNumber_UNIQUE` (`discountCardNumber` ASC) ,
CONSTRAINT `fk_Clients_DiscountCards1`
FOREIGN KEY (`discountCardNumber` )
REFERENCES `myschema`.`DiscountCards` (`cardNumber` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE TABLE `myschema`.`OrderStatuses` (
`statusID` INT NOT NULL AUTO_INCREMENT ,
`statusTitle` VARCHAR(45) NOT NULL ,
`statusDescription` VARCHAR(150) NULL ,
PRIMARY KEY (`statusID`) )
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `myschema`.`WorkstationUsers` (
`userID` INT NOT NULL AUTO_INCREMENT ,
`login` VARCHAR(45) NOT NULL ,
`pass` VARCHAR(45) NOT NULL ,
`name` VARCHAR(45) NOT NULL ,
`surname` VARCHAR(45) NOT NULL ,
`middleName` VARCHAR(45) NULL ,
PRIMARY KEY (`userID`) )
ENGINE = InnoDB;
CREATE TABLE `myschema`.`Orders` (
`orderID` BIGINT NOT NULL AUTO_INCREMENT ,
`registerDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`clientPhone` VARCHAR(15) NOT NULL ,
`shipmentAddress` VARCHAR(150) NOT NULL ,
`orderStatus` INT NOT NULL ,
`registrator` INT NOT NULL ,
PRIMARY KEY (`orderID`) ,
INDEX `fk_Orders_Clients` (`clientPhone` ASC) ,
INDEX `fk_Orders_OrderStatuses1` (`orderStatus` ASC) ,
INDEX `fk_Orders_WorkstationUsers1` (`registrator` ASC) ,
CONSTRAINT `fk_Orders_Clients`
FOREIGN KEY (`clientPhone` )
REFERENCES `myschema`.`Clients` (`phone` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Orders_OrderStatuses1`
FOREIGN KEY (`orderStatus` )
REFERENCES `myschema`.`OrderStatuses` (`statusID` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Orders_WorkstationUsers1`
FOREIGN KEY (`registrator` )
REFERENCES `myschema`.`WorkstationUsers` (`userID` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
It fails in last statement (CREATE TABLE Orders).
I already checked:
Types of refferencing tables are equals
Indexes on all columns exists
Engine is InnoDB
Thanks for any help! Have a good day!
P.S. sorry for possible duplicate. I really can't find any problem in my code.
Some of fields are defined as NOT NULL, but you defined 'ON DELETE' action as 'SET NULL'.
Make these fields nullabe -
CREATE TABLE `myschema`.`Orders` (
`orderID` BIGINT NOT NULL AUTO_INCREMENT ,
`registerDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`clientPhone` VARCHAR(15) NULL, -- NOT NULL ,
`shipmentAddress` VARCHAR(150) NOT NULL ,
`orderStatus` INT NULL, -- NOT NULL ,
`registrator` INT NULL, -- NOT NULL ,
PRIMARY KEY (`orderID`) ,
INDEX `fk_Orders_Clients` (`clientPhone` ASC) ,
INDEX `fk_Orders_OrderStatuses1` (`orderStatus` ASC) ,
INDEX `fk_Orders_WorkstationUsers1` (`registrator` ASC) ,
CONSTRAINT `fk_Orders_Clients`
FOREIGN KEY (`clientPhone` )
REFERENCES `myschema`.`Clients` (`phone` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Orders_OrderStatuses1`
FOREIGN KEY (`orderStatus` )
REFERENCES `myschema`.`OrderStatuses` (`statusID` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Orders_WorkstationUsers1`
FOREIGN KEY (`registrator` )
REFERENCES `myschema`.`WorkstationUsers` (`userID` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
In my case, the problem was solved by adding
DEFAULT CHARACTER SET = utf8
at the end of each create table
regards!