Shortcut Assign Primary Key while create table - mysql

What is the right way to assign primary key with shortcut query while creating table?
Here is the example how my shortcut it is:
create table booking_product (
`id` int(10) not null constraint `booking_product_id` primary key auto_increment ,
`bookingId` int(10) not null,
`serviceId` int(10) not null,
`date` date not null,
`price` decimal(30,15) not null,
`qty` int(1) not null,
`currencyId` int(10) not null,
`total` decimal(30,15) not null,
`roomInclusion` text null default null,
foreign key booking_product(bookingId) references booking(id) on update cascade on delete cascade,
foreign key booking_product(serviceId) references service(id) on update cascade on delete set null,
foreign key booking_product(currencyId) references currency(id) on update cascade on delete set null
) engine = InnoDB;
notice on line 2 I tried to assign primary key, but this query is wrong and produce error. If I try to only use id int(10) not null primary key auto_increment , I get error: Duplicate key name 'booking_product'

If you use constraint booking_product_id, you don't get errors about Duplicate key name 'booking_product' because the SQL parser stops at the first error.
Drop constraint booking_product_id and use
foreign key bookingId_fk(bookingId) references booking(id)
on update cascade
on delete cascade,
foreign key serviceId_fk(serviceId) references service(id)
on update cascade
on delete set null,
foreign key currencyId_fk(currencyId) references currency(id)
on update cascade
on delete set null

I know you picked an answer but when I simplified just your create statement to the code below I got it to work. Now with the added 'drop constraint' request by Oswald you might have everything you want:
create table booking_product (
id int(10) not null auto_increment,
PRIMARY KEY(id), <<<<< this worked for me...
bookingId int(10) not null,
serviceId int(10) not null,
date date not null,
price decimal(30,15) not null,
qty int(1) not null,
currencyId int(10) not null,
total decimal(30,15) not null,
roomInclusion text null default null)
Again I am only approaching the question from what you asked which was assigning a primary.
Hope this helps.

Related

Foreign Key constraint error even without a foreign key

I am getting the following error:
Error Code: 1215. Cannot add foreign key constraint
This happens even if I remove all foreign key constraints. timeline table does exist in the database, so that is not the issue.
Can't seem to figure out what would cause this problem
USE study;
CREATE TABLE IF NOT EXISTS timelineStage(
timelineStageID INT NOT NULL AUTO_INCREMENT,
timelineID TINYINT NOT NULL,
stageName VARCHAR(100) NOT NULL,
stagePredecessorID INT NULL,
isStartup TINYINT NOT NULL DEFAULT 0,
timelineStageNotes VARCHAR(500) NULL,
recCreatedByUserID INT NOT NULL,
recCreatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
recUpdatedByUserID INT NOT NULL,
recUpdatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (timelineStageID),
UNIQUE KEY IX_U_timelineStage_stageName(stageName, timelineID),
UNIQUE KEY IX_U_timelineStage_stagePredecessor(stagePredecessorID, timelineID),
CONSTRAINT FK_timelineStage_timelineID
FOREIGN KEY (timelineID)
REFERENCES timeline(timelineID)
ON UPDATE CASCADE,
CONSTRAINT FK_timelineStage_stagePredecessorID
FOREIGN KEY (stagePredecessorID)
REFERENCES timelineStage(timelineStageID)
ON UPDATE CASCADE,
CONSTRAINT FK_timelineStage_recCreatedByUserID
FOREIGN KEY (recCreatedByUserID)
REFERENCES customer.user(userID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_timelineStage_recUpdatedByUserID
FOREIGN KEY (recUpdatedByUserID)
REFERENCES customer.user(userID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ADDING Timeline and customer.user
USE study;
CREATE TABLE timeline(
timelineID TINYINT NOT NULL AUTO_INCREMENT,
timelineName VARCHAR(100) NOT NULL,
timelineNotes VARCHAR(500) NULL,
recCreatedByUserID INT(11) NOT NULL,
recCreatedTimeUTC DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
recUpdatedByUserID INT(11) NOT NULL,
recUpdatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (timelineID)
)
CREATE TABLE customer.user(
userID INT NOT NULL AUTO_INCREMENT,
firstName VARCHAR(100) NOT NULL,
lastName VARCHAR(100) NOT NULL,
emailAddress VARCHAR(100) NOT NULL,
PRIMARY KEY (userID))
The problem was with neither of the other tables. It was is study table (another table).
timelineStageID was set to TINYINT and in timelineStage table timelineStageID was set to INT.
Matching all to INT fixed the problem.
Carefully check every references clause whether the referenced column really is present in the table.
Also try to first create the table and then add the constraints one by one so you exactly know which one failed.
The problem is about this code: REFERENCES customer.user
You cannot create a foreign key constraint referencing a table in another database.

How to fix 'MySQL Error: 1822. Missing index for contraint' On creating a composite foreign key

I'm trying to create a table with a composite foreign key, but keep getting met with the error Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'fk_contractdateshistoric_contractdates_multiple' in the referenced table 'contractdates'
I'm using MySQL v8.0.16
I've checked if the column types are different, and I'm not sure what else could be the problem.
Here are the tables that make up the problem, All tables are made happily but the last one that contains the composite key causes the problem.
CREATE TABLE `contracts` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) DEFAULT NULL,
`CreationDate` datetime DEFAULT NULL,
`CreatedBy` varchar(30) DEFAULT NULL,
`CompletionDate` date DEFAULT NULL,
`Comments` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE `fieldheading` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`fieldTypeID` int(11) DEFAULT NULL,
`fieldCode` int(11) DEFAULT NULL,
`fieldHeading` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE `contractdates` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DateValue` datetime DEFAULT NULL,
`ContractID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `uq_contractdates_contractID_FieldHeading_ID` (`ContractID`,`FieldHeadingID`),
KEY `fk_contractdates_contracts_id_idx` (`ContractID`),
KEY `fk_contractdates_fieldheading_id_idx` (`FieldHeadingID`),
CONSTRAINT `fk_contractdates_fieldheading_id` FOREIGN KEY (`FieldHeadingID`) REFERENCES `fieldheading` (`id`),
CONSTRAINT `fk_contractdates_contracts_id` FOREIGN KEY (`ContractID`) REFERENCES `contracts` (`id`)
) COMMENT='Table to hold the dates for a contract, one row is one date for a specific contract';
CREATE TABLE `contractdateshistoric` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ContractID` int(11) NOT NULL,
`ContractDateCurrentID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
`ChangedByID` int(11) NOT NULL,
`DateValue` datetime NOT NULL,
`TimeStampChanged` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx` (`ContractID`, `FieldHeadingID`, `ContractDateCurrentID`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple` FOREIGN KEY (`ContractID`, `FieldHeadingID`, `ContractDateCurrentID`) REFERENCES `contractdates` (`contractid`, `fieldheadingid`, `id`)
) COMMENT='Audit trail of the dates';
Since you are using Composite FK in the table contractdates try adding composite index as well
KEY `fk_contractdates_mutiple_idx` (`ContractID`,`FieldHeadingID`,`ID`)
Whole create statement
CREATE TABLE `contractdates` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DateValue` datetime DEFAULT NULL,
`ContractID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `fk_contractdates_contracts_id_idx` (`ContractID`),
KEY `fk_contractdates_fieldheading_id_idx` (`FieldHeadingID`),
KEY `fk_contractdates_mutiple_idx` (`ContractID`,`FieldHeadingID`,`ID`),
CONSTRAINT `fk_contractdates_fieldheading_id` FOREIGN KEY (`FieldHeadingID`) REFERENCES `fieldheading` (`id`),
CONSTRAINT `fk_contractdates_contracts_id` FOREIGN KEY (`ContractID`) REFERENCES `contracts` (`id`)
) COMMENT='Table to hold the dates for a contract, one row is one date for a specific contract';
It's trying to tell you "you haven't created a necessary unique index on contractdates, that covers the columns (contractid, fieldheadingid, id) so I cannot create a foreign key on contractdateshistoric that refers to this set of columns when determining the single parent row"
I'm not sure why you're creating an fk that references 3 columns when contractdates has a pk that is just the ID column.
If a contractdateshistoric records refers to a single contractdates record as its parent, the historic record should have a contractdateid column that refers to contractdates.id - no need for multiple columns. Copy the pattern you used to relate a contractdates to its parent contract, and you'll be fine
I have tried by creating the keys individually for the columns, Please find the updated query:
CREATE TABLE `contractdateshistoric` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`ContractID` INT(11) NOT NULL,
`ContractDateCurrentID` INT(11) NOT NULL,
`FieldHeadingID` INT(11) NOT NULL,
`ChangedByID` INT(11) NOT NULL,
`DateValue` DATETIME NOT NULL,
`TimeStampChanged` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx` (`ContractID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx1` (`FieldHeadingID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx2` (`ContractDateCurrentID`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple` FOREIGN KEY (`ContractID`)
REFERENCES `contractdates` (`contractid`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple1` FOREIGN KEY (`FieldHeadingID`)
REFERENCES `contractdates` (`fieldheadingid`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple2` FOREIGN KEY (`ContractDateCurrentID`)
REFERENCES `contractdates` (`id`)
);
It works fine.

Mysql Connot add foreign key constraint. how can I resolve it?

I tried to excute the query. but a error was occurred. the error message is 'Cannot add foreign key constraint'.
I supposed to create this table. but it didn't work.
CREATE TABLE IF NOT EXISTS `mydb`.`member` (
`idseq` INT(1) NOT NULL AUTO_INCREMENT,
`id` VARCHAR(50) NOT NULL,
`pw` VARCHAR(20) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`mobile0` VARCHAR(3) NOT NULL,
`mobile1` VARCHAR(3) NOT NULL,
`mobile2` VARCHAR(4) NOT NULL,
`mobile3` VARCHAR(4) NOT NULL,
`birth` DATE NOT NULL,
`admin_YN` VARCHAR(45) NOT NULL DEFAULT 'N',
`reg_date` DATE NOT NULL,
`upd_date` DATE NOT NULL,
PRIMARY KEY (`idseq`, `id`))
ENGINE = InnoDB
AUTO_INCREMENT = 6
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `mydb`.`reservation` (
`reservation_seq` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` VARCHAR(50) NOT NULL,
`playMv_seq` INT(11) NOT NULL,
`reservaion_seat_code` VARCHAR(20) NOT NULL,
`reservaion_seat_num` INT(11) NOT NULL,
`reservation_charge` VARCHAR(20) NOT NULL,
`reservation_date` DATETIME NOT NULL,
PRIMARY KEY (`reservation_seq`, `user_id`, `playMv_seq`),
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
)
ENGINE = InnoDB
AUTO_INCREMENT = 8
DEFAULT CHARACTER SET = utf8;
So I checked it detail from a query'show engine innodb status. the detail error message is
Error in foreign key constraint of table mydb/reservation:
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
how can I resolve the error
You're trying to create a foreign key referencing the id column of the target table:
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
But what is the actual key on that target table?:
PRIMARY KEY (`idseq`, `id`)
It's not id, if the composite of idseq and id. In order to reference that as a foreign key, you need local columns which match that:
`user_idseq` INT(1) NOT NULL,
`user_id` VARCHAR(50) NOT NULL,
And use both of them for the foreign key:
FOREIGN KEY (`user_idseq`, `user_id`)
REFERENCES `mydb`.`member` (`idseq`, `id`)
(Side Note: That primary key in member looks pretty strange to me in the first place. Why can't idseq by itself be the primary key? What is the purpose of id?)

I cannot add 'null' in foreign key

I have created two tables, as shown below:
CREATE TABLE `leiame` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`number` INT(10) NOT NULL,
`title` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`) )
CREATE TABLE `download` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`id_leiame` INT(10) UNSIGNED NULL,
PRIMARY KEY (`id`),
CONSTRAINT `leia_id_fk` FOREIGN KEY (`id_leiame`)
REFERENCES `leiame` (`id`) ON UPDATE CASCADE )
When I add a null value for id_leiame on download, the following error occurs:
Cannot add or update a child row: a foreign key constraint fails (`bd`.`download`, CONSTRAINT `leia_id_fk` FOREIGN KEY (`id_leiame`) REFERENCES `leiame` (`id`) ON UPDATE CASCADE)
I set the id_leiame as NULL.
What I am missing?
As others pointed out in the comments, based on the statement you're executing, you seem to insert 'null' (i.e. a string containing null) instead of actual NULL, i.e. the absence of a value.
What you need to do is something along the lines of (not proper syntax)
if($leiame == "")
$crud->inserir("name,id_leiame", "'$name',null") << no single quotes!
else
$crud->inserir("name,id_leiame", "'$name','$leiame'")

on duplicate key update fails with error "Cannot add or update a child row"

I have a table with a compound primary key "name" and "id". The fields are actually "name","id","phone","amount","units","alias". I have the query
insert into MyTable (name,id,phone,amount) select "henry" as name, id,phone,amount from anotherTable
on duplicate key update phone=values(phone),amount=values(amount).
MySQL spits the following error:
Cannot add or update a child row: a foreign key constraint fails.
BTW, "id" is a foreign key.
Any help?
as requested below, the schema for other table is
CREATE TABLE `otherTable` (
`otherId` int(11) NOT NULL AUTO_INCREMENT,
`DOBId` int(11) NOT NULL,
`bankAccount` int(11) DEFAULT NULL,
`partialAmount` int(11) NOT NULL DEFAULT '0',
`id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`notes` varchar(299) DEFAULT NULL,
`latitude` decimal(8,5) DEFAULT NULL,
`longitude` decimal(8,5) DEFAULT NULL,
PRIMARY KEY (`otherId `),
KEY `DOBId ` (`DOBId `),
KEY `bankAccount ` (`bankAccount `),
KEY `id ` (`id `)
) ENGINE=InnoDB AUTO_INCREMENT=3305 DEFAULT CHARSET=utf8;
for myTable
CREATE TABLE `myTable` (
`name` int(11) NOT NULL,
`id` int(11) NOT NULL,
`appleNumber` int(11) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`windowsNumber` int(11) DEFAULT NULL,
`phone` int(11) DEFAULT NULL,
`pens` int(11) DEFAULT NULL,
`pencils` int(11) DEFAULT NULL,
PRIMARY KEY (`name`,`id`),
KEY `id` (`id`),
CONSTRAINT `myTable_ibfk_1` FOREIGN KEY (`id`) REFERENCES `yet_another` (`id`)
The problem appears to be that the FK constraint you have on myTable is referencing the ids of yet_another, so when you are inserting ids from anotherTable you are breaking this FK constraint. Chances are there are ids in anotherTable that do not exist in yet_another table.
Understand this is a shot in the dark, based on the abstracted schema you posted. If you want a more solid answer, I'd have to see the actual schema.
The on duplicate key applies to the primary key. I take it you're using innodb. This is failing on a foreign key constraint. Which values of you table MyTable are foreign keys? Please post the create statement for the table that shows all keys and constraints for more detailed help.
Just a guess, but for grins I'm betting it's a column that's not in the insert that is a foreign key not allowing a null value.