I'm having a problem creating a database in MySQL.
The error code:'Error code 1215: cannot add foreign key constraint' pops up when i try to implement my changes. I've paid attention to all the necessary things but i can't find the solution.
This error only happened after i added some tables after having made an initial database(which did work), so hopefully i'm not dealing with this problem throughout the whole project.
Here's a snippet of the code in which the error occurs, the foreign key that's not working correctly is 'tournament_id' referencing to 'id' in tournament:
CREATE DATABASE allin;
USE allin;
CREATE TABLE employee (
phone_number char(12) NOT NULL,
birth_date date NOT NULL,
tournament_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(phone_number),
FOREIGN KEY(tournament_id) REFERENCES tournament(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Second table:
CREATE TABLE tournament (
id int NOT NULL AUTO_INCREMENT,
date date NOT NULL,
time time NOT NULL,
cost decimal(5,2) NOT NULL,
min_players int NOT NULL,
min_age int NOT NULL,
max_age int NOT NULL,
location_id int NULL,
winner_id int NULL,
type varchar(40) NULL,
PRIMARY KEY(id),
FOREIGN KEY(winner_id) REFERENCES player(id) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY(location_id) REFERENCES event_location(id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The issue is here:
FOREIGN KEY(tournament_id) REFERENCES tournament(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
the above query is of CREATE TABLE employee. In this query, you are creating a FOREIGN KEY that refers to tournament(id), but as of now there is no tournament table exist in the specified database as the tournament table create query is reside below in the sequence.
I layman terms we can say, you are trying to refer a table column that
do not exist.
So to resolve this, run all you parent table creation query first, and than child table.
tournament_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(phone_number)
Hey, I don't think you could set another primary key while an "auto increment" already exist
Related
Lets say I have the following table:
CREATE TABLE IF NOT EXISTS tbl_mg_accounts (
account_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,L,
holder_id INT NOT NULL,
FOREIGN KEY (holder_id) REFERENCES tbl_mg_holders(holder_id) ON UPDATE CASCADE ON DELETE CASCADE
);
I want to add another column that auto-fills but it's based on a column within the foreign table reference.
E.g.
CREATE TABLE IF NOT EXISTS tbl_mg_accounts (
account_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,L,
holder_id INT NOT NULL,
username VARCHAR(50) NOT NULL,
test_col VARCHAR(100) GENERATED ALWAYS AS CONCAT(tbl_mg_holders.holder_name, username) VIRTUAL,
FOREIGN KEY (holder_id) REFERENCES tbl_mg_holders(holder_id) ON UPDATE CASCADE ON DELETE CASCADE
);
This is giving me an error...
Perhaps the addition of below is a syntax issue or is this actually a limitation with MySQL/MariaDB?
test_col VARCHAR(100) GENERATED ALWAYS AS CONCAT(tbl_mg_holders.holder_name, username) VIRTUAL
Ok Yes this seems like a limitation.
I've instead created a VIEW for my requirements and let the backend process this way.
when I wanted to generate tables, I got this error I don't know how to fix it. Is anyone face to this problem and how you solve it?
thanks
CREATE TABLE IF NOT EXISTS `tb_inv_detail` (
`inv_id_fk` INT UNSIGNED NOT NULL,
`part_id_fk` INT UNSIGNED NOT NULL,
`qty` DECIMAL(12,2) NOT NULL,
`tb_detailed` VARCHAR(50) NULL,
`tb_inv_detailcol` VARCHAR(45) NULL,
PRIMARY KEY (`inv_id_fk`),
INDEX `fk_tb_inv_detail_tb_parts1_idx` (`part_id_fk` ASC) VISIBLE,
CONSTRAINT `fk_tb_inv_detail_tb_parts1`
FOREIGN KEY (`part_id_fk`)
REFERENCES `tb_parts` (`part_id_pk`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tb_inv_detail_tb_invoice1`
FOREIGN KEY (`inv_id_fk`)
REFERENCES `tb_invoice` (`inv_id_pk`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 25 succeeded, 1 failed
Also this screenshot of my EER diagram:
Well the obvious code which is missing from what you posted above is the DDL for the two tables referred to by the foreign keys defined in tb_inv_detail. These tables are:
tb_parts
tb_invoice
These tables must be defined first, with correctly named primary key columns to match the foreign keys in your table above.
CREATE TABLE tb_parts (
part_id_pk INT UNSIGNED NOT NULL,
PRIMARY KEY (part_id_pk), -- referred to by part_id_fk
...
)
CREATE TABLE tb_invoice (
inv_id_pk INT UNSIGNED NOT NULL,
PRIMARY KEY (inv_id_pk), -- referred to by inv_id_fk
...
)
Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
i have customer table with nid_c,nama_customer, and more field ..
second table I have kendaraan with nopol,nid_c,nama_customer, and more field ..
I try make relation between this table..
I want update data nid_c and nama_customer on kendaraan table when I update customer table.
I got error message here.
Executing SQL script in server
ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
-- -----------------------------------------------------
-- Table `BengkelBiru`.`kendaraan`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `BengkelBiru`.`kendaraan` (
`NOPOL` VARCHAR(12) NOT NULL,
`NID_C` VARCHAR(7) NULL DEFAULT NULL,
`NAMA_CUSTOMER` VARCHAR(25) NULL DEFAULT NULL,
`MERK` VARCHAR(15) NULL DEFAULT NULL,
`TYPE` VARCHAR(25) NULL DEFAULT NULL,
`CC` VARCHAR(4) NULL DEFAULT NULL,
`TAHUN` VARCHAR(4) NULL DEFAULT NULL,
`WARNA` VARCHAR(10) NULL DEFAULT NULL,
`STATUS` VARCHAR(7) NULL DEFAULT NULL,
PRIMARY KEY (`NOPOL`),
INDEX `pkk_idx` (`NAMA_CUSTOMER` ASC, `NID_C` ASC),
CONSTRAINT `FK_NID_C`
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
SQL script execution finished: statements: 14 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
Your problem is on one or both of these lines:
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
^^^^^^^ Looks wrong s/b NAMA_CUSTOMER
I think you want this line:
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
to be
REFERENCES `BengkelBiru`.`customer` (`NAMA_CUSTOMER`, `NID_C`)
Why are you referring to NID_C twice in the reference? I say this because you define the foreign key as:
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
and your descriptions at the top shows customer having NID_C and NAMA_CUSTOMER as columns.
However, fundamentally, why do you have Nama_customer in the kendaraan (vehicle) table at all? This doesn't seem to be 3rd normal form. You've repeated the customer name in a second table; which isn't part of the Customer's PK. Now, this may be acceptable if you want to keep the name of the customer at the time the entry is made into kendaraan; but since you're making it part of the FK... and doing cascade update/delete... it's very odd.
So maybe you just want:
FOREIGN KEY (`NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
Assuming the Primary Key of Customer is NID_C
I dont think you can declare both at the same time. Try doing them separately.
CONSTRAINT `FK_NAMA_CUSTOMER`
FOREIGN KEY (`NAMA_CUSTOMER`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
CONSTRAINT `FK_NID_C`
FOREIGN KEY (`NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
There could be any possible scenario :-
1.Columns in the parent tables Can be INT UNSIGNED?
2.Data type in both tables should be same.
3.You are trying to reference a nonexistent key on the target table. Make sure that it is a key on the other table (it can be a primary or unique key).
Foregin Key Constaints
I have the following tables:
specie (MyIsam)
image (InnoDB)
specie_map (InnoDB)
The specie_map table should map an image to a specie, and therefore has the following columns:
specie_id
image_id
Both are int 11, just like the id columns of the specie and image tables. I know I can't create a foreign key between specie_id and specie=>id, since the specie table is a MyIsam table. However, I would expect it to be possible to create a foreign key between image_id and image=>id.
I can create that foreign key and it will save it, however, the CASCADE action I have associated with it does not work. When I delete an image, it does not delete the specie_map entry that is associated with it. I would expect this to work, as this foreign key is between InnoDB tables. Both columns are indexed and of the same data type.
Is this a limitation of MySQL, or am I doing something else wrong?
Update: as requested hereby the table definitions. I have snipped unimportant columns:
-- ----------------------------
-- Table structure for `image`
-- ----------------------------
DROP TABLE IF EXISTS `image`;
CREATE TABLE `image` (
`id` int(11) NOT NULL auto_increment,
`guid` char(36) default NULL,
`title` varchar(255) NOT NULL,
`description` text,
`user_id` int(11) NOT NULL,
`item_id` int(11) default NULL,
`date_uploaded` timestamp NOT NULL default '0000-00-00 00:00:00',
`date_created` timestamp NOT NULL default '0000-00-00 00:00:00',
`date_modified` timestamp NOT NULL default '0000-00-00 00:00:00',
`status` enum('softdeleted','tobedeleted','active') default 'active',
PRIMARY KEY (`id`),
KEY `image_user` (`user_id`),
KEY `image_item` (`item_id`),
KEY `image_mod_by` (`moderated_by`),
CONSTRAINT `image_mod_by` FOREIGN KEY (`moderated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `image_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='stores image data (not file data)';
-- ----------------------------
-- Table structure for `specie`
-- ----------------------------
DROP TABLE IF EXISTS `specie`;
CREATE TABLE `specie` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(256) NOT NULL,
`commonname` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=22 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
-- ----------------------------
-- Table structure for `specie_map`
-- ----------------------------
DROP TABLE IF EXISTS `specie_map`;
CREATE TABLE `specie_map` (
`id` int(11) NOT NULL auto_increment,
`image_id` int(11) NOT NULL,
`specie_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`karma` int(11) NOT NULL,
`date_created` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `image_id` (`image_id`),
KEY `specie_id` (`specie_id`),
CONSTRAINT `specie_map_ibfk_1` FOREIGN KEY (`image_id`) REFERENCES `image` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Foreign keys works only with InnoDb in mysql. MyISAM doesn't support them (the statements are ignored).
And is there any reason why you mix multiple DB engines?
I think you should post the exact DDL statements you used when you attempted to create these tables and the foreign key. Foreign keys between innodb tables work fine, but there are still a few things to look out for:
0) Both tables must be InnoDB. This was already highlighted by the other posters and this is probably the immediate cause of your problem.
1) the data type of the referencing columns (those that make up the foreign key) and their respective referenced columns should be the same. For example, you can't create a foreign key constrain on an INT UNSIGNED column to a plain INT column.
2) if the foreign key is created as part of the table DDL, be sure to put the foreign key definition in the constraints section, that is, below all column definitions. For example:
CREATE TABLE parent (
id int unsigned PRIMARY KEY
);
CREATE TABLE child (
parent_id int unsigned
, foreign key (parent_id)
references parent (id)
);
will work but this:
CREATE TABLE child (
parent_id int unsigned
foreign key references parent (id)
);
won't. It will fail silently because MySQL's parser ignores these types of constraint definitions even before InnoDB gets to create the table (silly, but that's how it is)
3) There must be an index over all the referenced columns. Usually the referenced columns will together make up a primary key or a unique constraint anyway, but it is your job to define this before defining the foreign key.
Final word of advice: if you think your DDL is ok but you still get an error when you execute it, for example like this:
ERROR 1005 (HY000): Can't create table 'test.child' (errno: 150)
Warning (Code 150): Create table 'test/child' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns.
Error (Code 1005): Can't create table 'test.child' (errno: 150)
Then these errors may still not reveal the true nature of the error (silly again, but that's how it is). To shed more light on it, run this command immediately after your attempt to create the foreign key:
SHOW ENGINE INNODB STATUS;
This will give you a bunch of status info, and one section there looks like this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
120122 11:38:28 Error in foreign key constraint of table test/child:
foreign key (parent_id) references parent (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.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
As you can see, this gives a bit more information and reveals the true problem, namely "column types in the table and the referenced table do not match for constraint"
So please, post your actual DDL, I'm sure there is a problem in there somewhere.