I've exported a database from Access to a MySQL server (local)
While doing this it did not export the foreign keys I had assigned in the database with them. While inconvenient I thought it didn't matter since I could add them manually. However when I use the following command:
alter table betalingsstatus
add foreign key (bedrijf_id)
references bedrijven(bedrijf_id)
It says it successfully did add the constraint. However when I insert something into the table and I add a number that isn't in the table bedrijven it still inserts it. I had the same problem with other foreign keys I have in the database.
Put ENGINE=INNODB; after the creation - altering of those tables that you want to enforce the foreign key constraints.
Example:
CREATE TABLE mytbl
(
id int PRIMARY KEY AUTO_INCREMENT,
name varchar(10) NOT NULL
) ENGINE=INNODB;
Related
I'm relatively new to MySQL syntax. I'm trying to set up a database with different schemas. For convenience I structured my code in two parts:
in the first part I'm creating the tables in each schema without imposing foreign key constraints
in the second part I'm writing ALTER TABLE commands to create foreign key relations.
When it comes to create a foreign key constraint for an ID in a table that point to a table in another schema I get
"Error Code: 1824. Failed to open the referenced table 'schema_a.table_a".
Practically, I've done this:
#First part
CREATE SCHEMA `schema_a`
USE `schema_a`;
CREATE TABLE `table_a`
(
IDa INTEGER NOT NULL,
...
PRIMARY KEY(`IDa`)
)ENGINE=InnoDB, CHARSET=..., Collate=...;
CREATE SCHEMA `schema_b`
USE `schema_b`;
CREATE TABLE `table_b`
(
IDb INTEGER NOT NULL,
IDa INTEGER NOT NULL,
...
PRIMARY KEY(`IDb`)
)ENGINE=InnoDB, CHARSET=..., Collate=...;
#Second part
USE `Schema_b`;
ALTER TABLE `table_b`
ADD CONSTRAINT `FK_IDa` FOREIGN KEY (`IDa`) REFERENCES `schema_a.table_a`(`IDa`) ON DELETE CASCADE ON UPDATE CASCADE;
I'm not even sure if it is formally correct to create external foreign keys.
Does anyone have any suggestions to solve this problem?
Thanks!
`schema_a.table_a` means one identifier, i.e. MySQL assumes that only the table name is schema_a.table_a. You need to quote each part of a multi part identifier individually like in `schema_a`.`table_a`.
ALTER TABLE `table_b`
ADD CONSTRAINT `FK_IDa`
FOREIGN KEY (`IDa`)
REFERENCES `schema_a`.`table_a`
(`IDa`)
ON DELETE CASCADE
ON UPDATE CASCADE;
Or you can just not quote in your particular case.
I have two tables as follow:
1st Table:
CREATE TABLE User (
User_ID VARCHAR(8)NOT NULL PRIMARY KEY,
User_Name VARCHAR (25) NOT NULL,
User_Gender CHAR (1) NOT NULL,
User_Position VARCHAR (10) NOT NULL,
);
2nd table:
CREATE TABLE Training (
Training_Code VARCHAR(8) NOT NULL Primary Key,
Training_Title VARCHAR(30) NOT NULL,
);
I am trying to create a table which has two foreign keys to join both of the previous tables:
CREATE TABLE Request (
User_ID VARCHAR(8) NOT NULL,
Training_Code VARCHAR(8) NOT NULL,
Request_Status INT(1) NOT NULL
);
When I am trying to set the foreign keys in the new table, the User_ID can be done successfully but the Training_Code cannot be set to foreign key due to the error:
ERROR 1215 (HY000): Cannot add foreign key constraint
As I searched for this problem, the reason for it, is that data type is not the same, or name is not the same.. but in my situation both are correct so could you tell me what is wrong here ?
You need an index for this column in table Request too:
Issue first
CREATE INDEX idx_training_code ON Request (Training_Code);
Then you should be successful creating the foreign key constraint with
ALTER TABLE Request
ADD CONSTRAINT FOREIGN KEY idx_training_code (Training_Code)
REFERENCES Training(Training_Code);
It worked for me. But I've got to say that it worked without create index too, as the documentation of Using FOREIGN KEY Constraints states:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Emphasis by me. I don't know what's the issue in your case.
Demo
Explanation of the issue
The behavior mentioned in the question can be reproduced if the table Training is using the MyISAM storage engine. Then creating a foreign key referencing the table Training will produce the mentioned error.
If there's data in the table, then simple dropping of the table would not be the best solution. You can change the storage engine to InnoDB with
ALTER TABLE Training Engine=InnoDB;
Now you can successfully add the foreign key constraint.
I am in the process of designing the databases for my system. There are a lot of foreign key constraints.
I was wondering whether I could get some advice, whether I should do which of the following:
1) Specify the constraints during table creation itself ie,
CREATE TABLE IF NOT EXISTS abc
(
keyword VARCHAR(20) NOT NULL,
id INT UNSIGNED NOT NULL,
FOREIGN KEY (id) REFERENCES xyz(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
2)create the table without FK constraints and 'alter' the table later on ie,
CREATE TABLE IF NOT EXISTS abc
(
keyword VARCHAR(20) NOT NULL,
id INT UNSIGNED NOT NULL,
)ENGINE=InnoDB;
ALTER TABLE abc ADD CONSTRAINT fk_constraint FOREIGN KEY (id) REFERENCES xyz(id)
ON DELETE CASCADE ON UPDATE CASCADE;
Table xyz is simply another table with 'id' as a primary key.
You may create the FK at once. But this is not always possible because they can refer to each other in a circular fashion. Also, you may want to add columns later, with a FK.
It may be slightly faster to add it at once, because MySQL has to validate and rebuild the table structure for some changes (although I'm not sure adding FKs is one of those). But this process will be reasonably fast on empty tables, so it doesn't matter much when you add the FK.
The result will be the same. So, there is no differences.
If I create new database, I'd create table and its foreign key in one statement. The script will look better. But in this case parent tables must be created before the child tables.
If you don't want to take into account dependencies when creating tables, you can create tables in random order in the beginning of the script and then add foreign keys using ALTER TABLE.
I'm creating a table that has a basisId field as the primary key. There's also another field parentBasis which would be a reference to another tuple with that.basisId equal to this.parentBasis. What I want to do to is express this constraint while creating the table.
Something like: ADD CONSTRAINT CHECK EXISTS this.parentBasis AS somewhere.basisId (Obviously not real MySQL).
A quick browse through the MySQL dev pages didn't do much good. Any help would be appreciated.
Thanks.
If you're using InnoDB then you can create a foreign key from the table to itself. For example:
create table t (
id int not null primary key,
parent int null
);
alter table t add constraint foreign key (parent) references t(id);
then t.parent would either have to be NULL or a t.id value.
So I am trying to add a primary key to one of the tables in my database. Right now it has a primary key like this:
PRIMARY KEY (user_id, round_number)
Where user_id is a foreign key.
I am trying to change it to this:
PRIMARY KEY (user_id, round_number, created_at)
I am doing this in phpmyadmin by clicking on the primary key icon in the table structure view.
This is the error I get:
#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)
It is a MySQL database with InnoDB table engine.
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section.
As was said you need to remove the FKs before. On Mysql do it like this:
ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;
ALTER TABLE `table_name` DROP INDEX `id_name_fk`;
For those who are getting to this question via google... this error can also happen if you try to rename a field that is acting as a foreign key.
To bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming the attribute.
(For PHPMyAdmin users: To remove FK constrains in PHPMyAdmin, select the attribute then click "relation view" next to "print view" in the toolbar below the table structure)
If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.
SHOW CREATE TABLE alarm;
Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`) line.
ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
ALTER TABLE `alarm` DROP `server_id`
This will delete the foreign key server from the Alarms table.
I had this problem, it is for foreign-key
Click on the Relation View (like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB) column, just put the select to nothing! Means no foreign-key
Hope that works!
If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.
Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.
You can set some value which is present in the parent table and then adding foreign key worked for me.