I am trying to using Nodejs sequelize to create database. The commands being invoked are
CREATE TABLE IF NOT EXISTS `wheel` (`id` INTEGER NOT NULL auto_increment , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `shopId` VARCHAR(255), PRIMARY KEY (`id`),
FOREIGN KEY (`shopId`) REFERENCES `shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `segments` (`segmentID` VARCHAR(255) NOT NULL , `heading` VARCHAR(255) NOT NULL, `subHeading` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `wheelId` INTEGER, PRIMARY KEY (`segmentID`),
FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `shop` (`id` VARCHAR(255) NOT NULL , `accessToken` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
But I get this error
Unhandled rejection SequelizeDatabaseError: ER_CANNOT_ADD_FOREIGN:
Cannot add foreign key constraint
When I try to see the last foreign key error , it says
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2016-07-28 19:23:21 0x700000d95000 Error in foreign key constraint of table exitpopup/segments:
FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB:
Cannot resolve table name close to:
(`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB
Strangely, When I put the sql statements in sql console , it works and there isn't any error.
What am I doing wrong ?
The order needs to change. You are creatig the wheel table before you have created the shop table. However wheel refers to the shop table which does not exists in your original set of queries. When you change the order the shop table already exists so the error does not occur.
CREATE TABLE IF NOT EXISTS `shop`
(`id` VARCHAR(255) NOT NULL , `accessToken` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `wheel`
(`id` INTEGER NOT NULL auto_increment , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `shopId` VARCHAR(255),
PRIMARY KEY (`id`),
FOREIGN KEY (`shopId`) REFERENCES `shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `segments`
(`segmentID` VARCHAR(255) NOT NULL , `heading` VARCHAR(255) NOT NULL, `subHeading` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `wheelId` INTEGER,
PRIMARY KEY (`segmentID`),
FOREIGN KEY (`wheelId`) REFERENCES `wheel` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
If you need to turn off this check, because you're importing a bunch of tables from a dump from another DB, you want to run:
set FOREIGN_KEY_CHECKS=0
As if it was a SQL statement. So for me in Sequelize I ran:
let promise = sequelize.query("set FOREIGN_KEY_CHECKS=0");
This is because of mainly following 2 reasons
1. When the primary key data type and the foreign key data type did not match.
return sequelize.define('Manager', {
id: {
type: DataTypes.INTEGER(11), // The data type defined here and
references: {
model: 'User',
key: 'id'
}
}
}
)
return sequelize.define('User', {
id: {
type: DataTypes.INTEGER(11), // This data type should be the same
}
}
)
2. When the referenced key is not a primary or unique key.
return sequelize.define('User', {
id: {
primaryKey: true
},
mail: {
type: DataTypes.STRING(45),
allowNull: false,
primaryKey: true // You should change this to 'unique:true'. you cant have two primary keys in one table.
}
}
)
It's possible your char encoding is different between the foreign key and the original key. Check your schema.
Declare your foreign key like this.
class Team extends Model {
static associate({ Player }) {
this.hasMany(Player, { foreignKey: 'playerId', onDelete: 'CASCADE' });
}
}
class Player extends Model {
static associate({ Team }) {
this.belongsTo(Team, {foreignKey: 'playerId', onDelete: 'CASCADE', targetKey: 'id',
});
}
}
The onDelete: 'CASCADE' is important.
Related
While trying to run the following query:
UPDATE Flight
SET FLNO = '1001'
WHERE FLNO = '1000';
I receive the following error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`user/FlightLegInstance`, CONSTRAINT `FlightLegInstance_ibfk_1` FOREIGN KEY (`FLNO`) REFERENCES `FlightLeg` (`FLNO`) ON UPDATE CASCADE)
The following are my creation queries:
Flight:
CREATE TABLE Flight (
FLNO INTEGER NOT NULL,
Meal varchar(50) NOT NULL,
Smoking char(1) NOT NULL,
PRIMARY KEY (FLNO)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
FlightLeg:
CREATE TABLE FlightLeg (
FLNO INTEGER NOT NULL,
Seq char(25) NOT NULL,
FromA char(3) NOT NULL,
ToA char(3) NOT NULL,
DeptTime DATETIME NOT NULL,
ArrTime DATETIME NOT NULL,
Plane INTEGER NOT NULL,
PRIMARY KEY (FLNO, Seq),
FOREIGN KEY (FLNO) REFERENCES Flight(FLNO) ON UPDATE CASCADE,
FOREIGN KEY (FromA) REFERENCES Airport(Code),
FOREIGN KEY (ToA) REFERENCES Airport(Code)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
FlightLegInstance:
CREATE TABLE FlightLegInstance (
Seq char(25) NOT NULL,
FLNO INTEGER NOT NULL,
FDate DATE NOT NULL,
ActDept DATETIME NOT NULL,
ActArr DATETIME NOT NULL,
Pilot INTEGER NOT NULL,
PRIMARY KEY (Seq, FLNO, FDate),
FOREIGN KEY (FLNO) REFERENCES FlightLeg(FLNO) ON UPDATE CASCADE,
FOREIGN KEY (FLNO, FDate) REFERENCES FlightInstance(FLNO, FDate) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I would assume that the error is in one of the two FK definitions of FlightLegInstance, but I'm not sure. Can anyone help me with this?
Thanks.
this is not working just because you have defind [flno] column in second table as foriegn key
the solution of this problem is you have to update it at both places
thanks
I have an error with the following SQL query and I'm not sure how to fix it. The error message is:
"Error Code: 1022. Can't write; duplicate key in table
't_course_catalog'"
Here is the query:
CREATE TABLE IF NOT EXISTS `TrainingPlan`.`T_Course_Catalog` (
`CC_ID` INT NOT NULL AUTO_INCREMENT,
`ID_Catalog_Level` INT NOT NULL,
`Catalog_Name` VARCHAR(50) NOT NULL,
`ID_Delivery_Method` INT NOT NULL,
`Created_Date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Created_By` VARCHAR(8) NOT NULL,
`Modified_Date` TIMESTAMP NULL,
`Modified_By` VARCHAR(8) NULL,
`Deleted` TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`CC_ID`),
INDEX `fk_cl_idx` (`ID_Catalog_Level` ASC),
INDEX `fk_dm_idx` (`ID_Delivery_Method` ASC),
CONSTRAINT `fk_cl`
FOREIGN KEY (`ID_Catalog_Level`)
REFERENCES `TrainingPlan`.`T_Catalog_Level` (`CL_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_dm`
FOREIGN KEY (`ID_Delivery_Method`)
REFERENCES `TrainingPlan`.`T_Delivery_Method` (`DM_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
It should be no problem to reference the foreign keys because the reference table exists.
Try renaming your constraints, they are probably duplicated somewhere in your database.
Example :
fk_cl becomes fk_course_catalog_cl
fk_dm become fk_course_catalog_dm
Or w/e alternative name you want it to be.
I am trying to create a database with multiple foreign keys with delete/ update constraints, but I got a error code 1005 with following sql scripts:
CREATE TABLE Worker (
WorkerID smallint auto_increment,
WorkerType varchar(45) NOT NULL,
WorkerName varchar(45) NOT NULL,
Position varchar(45) NOT NULL,
TaxFileNumber int NOT NULL,
Address varchar(100) ,
Phone varchar(20) ,
SupervisorID smallint ,
PRIMARY KEY (WorkerID),
FOREIGN KEY (SupervisorID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
CREATE TABLE Grape (
GrapeID smallint NOT NULL,
GrapeType varchar(45) NOT NULL,
JuiceConversionRatio int,
StorageContainer ENUM('Stainless Steel Tank','Oak Barrel'),
AgingRequirement int,
PRIMARY KEY (GrapeID)
)Engine=InnoDB;
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint NOT NULL,
GrapeID smallint NOT NULL,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
The error code says that fail to create the Vineyard table, I just want to know the proper format for creating multiple foreign keys with delete/update control.
Your foreign key rule is ON DELETE SET NULL but your column definition is NOT NULL.
Either change your column definition and remove the NOT NULL part or overthink your foreign key rule. That works:
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint,
GrapeID smallint,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
SQLFiddle demo
Try with create table(innoDB enginer) without foreign key and use the update table with constraint syntax, for example:
ALTER TABLE `vineyard`
ADD CONSTRAINT `relation_farmer_has_many_vineyards`
FOREIGN KEY (`farmer_id`)
REFERENCES `worker` (`worker_id`)
ON DELETE SET NULL
ON UPDATE CASCADE;
Reference:
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
Trick: is not recommended to use capital letters(or camel case) in the names of the tables that the behavior differs from the operating system being used:
http://dev.mysql.com/doc/refman/5.1/en/identifier-case-sensitivity.html
Visit :
https://developer.android.com/training/basics/data-storage/databases.html#DefineContract
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Visit :
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
CREATE TABLE `ffxi_characterJob` (
`serverID` int(11) NOT NULL,
`userid` int(10)unsigned NOT NULL,
`characterName` varchar(255) NOT NULL,
`jobAbbr` char(4) NOT NULL,
`jobLevel` int(11) default '0',
PRIMARY KEY (`serverID`,`userid`,`characterName`,`jobAbbr`),
INDEX (`jobAbbr`),
CONSTRAINT FOREIGN KEY (`serverID`,`userid`,`characterName`) REFERENCES `ffxi_characters` (`serverID`,`userid`,`characterName`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (`jobAbbr`) REFERENCES `ffxi_jobType` (`jobAbbr`) ON DELETE CASCADE ON UPDATE CASCADE
) TYPE=InnoDB;
I want to create a database and connect it with two database. But I don't know when i create the Foreign Key to the second database (time_shift table) it always result error 150;
Here is the structure of table outlet:
And this is structure of table time_shift:
And this the query to create new table tide_cart:
create table `tide_chart` (
`id` int(10) not null auto_increment primary key,
`date` date null,
`outletId` int(11) not null,
`timeShiftId` int(11) not null,
`value` varchar(255) not null,
unique (`date`, `outletId`, `timeShiftId`),
foreign key (`outletId`) references `outlet`(`id`)
ON update cascade ON delete cascade,
foreign key (`timeShiftId`) references `time_shift`(`id`)
ON update cascade ON delete cascade
) engine=innoDB;
Please explain to me, why i get error when try to make foreign key connect to table time_shift?
Update: add dump export structure table for outlet and time_shift:
CREATE TABLE `outlet` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
CREATE TABLE `time_shift` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`time_start` time NOT NULL,
`time_end` time NOT NULL,
`is_active` tinyint(4) NOT NULL DEFAULT '1',
`ref_area` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `ref_area` (`ref_area`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
You need to use the InnoDB engine for your tables. time_shift is using MyISAM.
You must define indexes for outletId and timeShiftId (either UNIQUE or KEY as needed) in order to be able to create a foreign key using that field.
Trying to help an intern with her project. She wants to add foreign keys to an existing table but this query:
ALTER TABLE `document`
ADD CONSTRAINT `document_ibfk_1` FOREIGN KEY (`cle_author`)
REFERENCES `author` (`id_author`)
ON DELETE CASCADE
ON UPDATE CASCADE;
gives this error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`wrc_mysql`.<result 2 when explaining filename '#sql-30e4_7000d'>, CONSTRAINT `document_ibfk_1` FOREIGN KEY (`cle_author`) REFERENCES `author` (`id_author`) ON DELETE CASCADE ON UPDATE CASCADE)
Schema are like so
CREATE TABLE `document` (
`id_document` int(11) NOT NULL AUTO_INCREMENT,
`abstract` text,
`number_of_pages` int(10) DEFAULT NULL,
`original_surrey_citation` varchar(255) DEFAULT NULL,
`updated_citation` varchar(255) DEFAULT NULL,
`library_of_congress` varchar(10) DEFAULT NULL,
`cross_citation` varchar(50) DEFAULT NULL,
`doc_type` varchar(255) DEFAULT NULL,
`questions` varchar(255) DEFAULT NULL,
`keywords` varchar(255) DEFAULT NULL,
`cle_author` int(10) NOT NULL,
PRIMARY KEY (`id_document`),
KEY `cle_author` (`cle_author`)
) ENGINE=InnoDB AUTO_INCREMENT=22591 DEFAULT CHARSET=utf8
CREATE TABLE `author` (
`id_author` int(10) NOT NULL AUTO_INCREMENT,
`author_name` varchar(255) DEFAULT NULL,
`sender_office` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id_author`),
KEY `author_name` (`author_name`,`sender_office`)
) ENGINE=InnoDB AUTO_INCREMENT=22591 DEFAULT CHARSET=utf8
Anyone know what is going wrong?
You probably have inconsistent data between your two tables. This error means that you have a cle_author value in your document table that doesn't have a corresponding entry in the author table. Since the cle_author value is going to be set up as a foreign key, each value for that field must have a corresponding entry in the author table's id_author field.
Per this page: Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails
checked intern's data with
SELECT cle_author FROM document doc
LEFT JOIN author a ON doc.cle_author=a.id_author
WHERE a.id_author IS NULL;
And found ALL of her cle_author data is bogus and does not hold valid references to id_author values.