I have a database, I used these commands :
CREATE TABLE APPOINTMENT (app_id INT(5) NOT NULL, app_doctor INT(5) NOT NULL, app_date DATE, PRIMARY KEY (app_id));
CREATE TABLE APPPATIENTS (patient_ssn INT(10) NOT NULL, patient_name VARCHAR(20) NOT NULL, sex CHAR(1) NOT NULL, appointment_id INT(5), PRIMARY KEY (patient_ssn), UNIQUE (appointment_id));
ALTER TABLE APPPATIENTS ADD FOREIGN KEY (appointment_id) REFERENCES APPOINTMENT(app_id) ON DELETE CASCADE;
Now, I want to delete foreign key appointment_id in appPatients table :
ALTER TABLE apppatients DROP FOREIGN KEY appointment_id;
But I got an error :
Can't drop 'appointment_id'; check that column/key exists.
It is there! How can it give that error? What am I doing wrong?
I tried to create a database with your code and I notice the foreign key name appears different from appointment_id: reading with more attention the command definition, I notice that when you write
ADD FOREIGN KEY (appointment_id)
you are only saying the column on which the constraint will be created, not its name.
You can read the specifications here:
SQL FOREIGN KEY Constraint on ALTER TABLE
So, if you want to specify the name of the key, you have to write, for example:
alter table APPPATIENTS
ADD CONSTRAINT appointment_key
FOREIGN KEY (appointment_id)
REFERENCES appointment(app_id) ON DELETE CASCADE;
And so you know the name of the foreign key you created (appointment_key in this case).
If you want to know the foreign key name generated by mysql you can use the command
show create table APPPATIENTS;
that shows the complete table definition.
Related
im new on mysql workbench, and i tried so many things to put my script working but i simply cant... Ive got these tables:
CREATE TABLE Utilizador (email varchar(40) not null, nome varchar(50)
not null, dataNascimento date, profissao varchar(50) not null,
reputacao double(3,2) unsigned not null, constraint pk_Utilizador
primary key(email))
This is the first table created!
CREATE TABLE POI (email varchar(40) not null, designacaoPOI
varchar(10) not null, coordenadaX int, coordenadaY int,
descricaoPOI varchar(200), constraint pk_POI primary key(email,
designacaoPOI), constraint fk_POI foreign key(email) references
Utilizador(email) on delete cascade)
This is the second table created!
CREATE TABLE Utilizador_POI (email varchar(40) not null, designacaoPOI
varchar(10) not null, constraint pk_Utilizador_POI primary key(email,
designacaoPOI), constraint fk1_Utilizador_POI foreign key(email)
references Utilizador(email) on delete cascade, constraint
fk2_Utilizador_POI foreign key(designacaoPOI) references
POI(designacaoPOI) on delete cascade)
This table gives me the error: Error Code: 1215. Cannot add foreign key constraint
I did some tests and im almost sure that the problem is in the foreign key "designacaoPOI". The other FK ("email") dont give me any error, so maybe the problem is in the Table POI?
Thanks in advanced!
The problem here is twofold:
1/ Use IDs for PRIMARY KEYs
You should be using IDs for primary keys rather than VARCHARs or anything that has any real-world "business meaning". If you want the email to be unique within the Utilizador table, the combination of email and designacaoPOI to be unique in the POI table, and the same combination (email and designacaoPOI) to be unique in Utilizador_POI, you should be using UNIQUE KEY constraints rather than PRIMARY KEY constraints.
2/ You cannot DELETE CASCADE on a FOREIGN KEY that doesn't reference the PRIMARY KEY
In your third table, Utilizador_POI, you have two FOREIGN KEYs references POI. Unfortunately, the PRIMARY KEY on POI is a composite key, so MySQL has no idea how to handle a DELETE CASCADE, as there is not a one-to-one relationship between the FOREIGN KEY in Utilizador_POI and the PRIMARY KEY of POI.
If you change your tables to all have a PRIMARY KEY of ID, as follows:
CREATE TABLE blah (
id INT(9) AUTO_INCREMENT NOT NULL
....
PRIMARY KEY (id)
);
Then you can reference each table by ID, and both your FOREIGN KEYs and DELETE CASCADEs will work.
I think the problem is that Utilizador_POI.email references POI.email, which itself references Utilizador.email. MySQL is probably upset at the double-linking.
Also, since there seems to be a many-to-many relationship between Utilizador and POI, I think the structure of Utilizador_POI isn't what you really want. Instead, Utilizador_POI should reference a primary key from Utilizador, and a matching primary key from POI.
The problem is in your second table. Your primary key is (email,designacaoPOI), when you try to reference that in your table it gives you error because of this:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
For it to work, either change the order of your second tale PRIMARY KEY :
CREATE TABLE POI (
email VARCHAR(40) NOT NULL,
designacaoPOI VARCHAR(10) NOT NULL,
coordenadaX INT,
coordenadaY INT,
descricaoPOI VARCHAR(200),
CONSTRAINT pk_POI PRIMARY KEY (designacaoPOI,email), -- changed the order
CONSTRAINT fk_POI FOREIGN KEY (email)
REFERENCES Utilizador(email) ON DELETE CASCADE
);
sqlfiddle demo
or add an index for designacaoPOI:
CREATE TABLE POI (
email VARCHAR(40) NOT NULL,
designacaoPOI VARCHAR(10) NOT NULL,
coordenadaX INT,
coordenadaY INT,
descricaoPOI VARCHAR(200),
CONSTRAINT pk_POI PRIMARY KEY (designacaoPOI,email),
KEY key_designacaoPOI(designacaoPOI), -- added index for that column
CONSTRAINT fk_POI FOREIGN KEY (email)
REFERENCES Utilizador(email) ON DELETE CASCADE
);
sqlfiddle demo
Either of these solutions will let you create your third table without errors.
I am getting the above error when I execute the following query.
CREATE TABLE doctor
(
id varchar(6) NOT NULL,
Specialization varchar(15) NOT NULL,
FOREIGN KEY(id) REFERENCES employee(id)
on delete cascade on update cascade
);
Where is the problem?
You need an index on employee(id) and before you add any FK pointing at it. You also need one on doctor(id). In both cases, a primary key seems like a good option.
Don't forget that in the CREATE TABLE script, the PRIMARY KEY should appear before the FOREIGN KEY instruction.
See this post for a quick how-to: How to add a primary key to a MySQL table?
I'm not sure what I'm doing wrong here, but I get an error:
Error Code: 1005. Can't create table 'erm.section' (emo:150)
Here is the code. The 'course' table is created successfully. I tried modifying the name of the course_number attritube in the 'section' table but that didn't work.
USE erm;
CREATE TABLE course
(
course_name VARCHAR(30) NOT NULL,
course_number VARCHAR(20) NOT NULL,
credit_hours INT NOT NULL,
department VARCHAR(10),
CONSTRAINT course_pk PRIMARY KEY (course_name)
);
CREATE TABLE section
(
section_identifier INT NOT NULL,
course_number VARCHAR(20),
semester VARCHAR(10) NOT NULL,
school_year VARCHAR(4) NOT NULL,
instructor VARCHAR(25),
CONSTRAINT section_pk PRIMARY KEY (section_identifier),
CONSTRAINT section_fk FOREIGN KEY (course_number)
REFERENCES course (course_number)
ON DELETE SET NULL
ON UPDATE CASCADE
);
course_number is not a primary key in the table course.
the foreign key in the table section must reference a primary key form another table.
You have to create an index on the column referenced by the foreign key:
alter table course add index (course_number);
(It doesn't have to be a primary key index.) From the MySQL documentation:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
AFAIK, dropping the CONSTRAINT, then rename, then add the CONSTRAINT back is the only way. Backup first!
to drop it use this
ALTER TABLE section
DROP FOREIGN KEY course_number
and to add it again use this
ALTER TABLE section
ADD FOREIGN KEY (course_number)
REFERENCES course (course_number)
I want to add a Foreign Key to a table called "katalog".
ALTER TABLE katalog
ADD CONSTRAINT `fk_katalog_sprache`
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
When I try to do this, I get this error message:
Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)
Error in INNODB Status:
120405 14:02:57 Error in foreign key constraint of table
mytable.#sql-7fb1_7d3a:
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL:
Cannot resolve table name close to:
(`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL
When i use this query it works, but with wrong "on delete" action:
ALTER TABLE `katalog`
ADD FOREIGN KEY (`Sprache` ) REFERENCES `sprache` (`ID` )
Both tables are InnoDB and both fields are "INT(11) not null". I'm using MySQL 5.1.61. Trying to fire this ALTER Query with MySQL Workbench (newest) on a MacBook Pro.
Table Create Statements:
CREATE TABLE `katalog` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`AnzahlSeiten` int(4) unsigned NOT NULL,
`Sprache` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `katalogname_uq` (`Name`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC$$
CREATE TABLE `sprache` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Bezeichnung` varchar(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Bezeichnung_UNIQUE` (`Bezeichnung`),
KEY `ix_sprache_id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
To add a foreign key (grade_id) to an existing table (users), follow the following steps:
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
Simply use this query, I have tried it as per my scenario and it works well
ALTER TABLE katalog ADD FOREIGN KEY (`Sprache`) REFERENCES Sprache(`ID`);
Simple Steps...
ALTER TABLE t_name1 ADD FOREIGN KEY (column_name) REFERENCES t_name2(column_name)
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
But your table has:
CREATE TABLE `katalog` (
`Sprache` int(11) NOT NULL,
It cant set the column Sprache to NULL because it is defined as NOT NULL.
check this link. It has helped me with errno 150:
http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/
On the top of my head two things come to mind.
Is your foreign key index a unique name in the whole database (#3 in the list)?
Are you trying to set the table PK to NULL on update (#5 in the list)?
I'm guessing the problem is with the set NULL on update (if my brains aren't on backwards today as they so often are...).
Edit: I missed the comments on your original post. Unsigned/not unsigned int columns maybe resolved your case. Hope my link helps someone in the future thought.
How to fix Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150) in mysql.
alter your table and add an index to it..
ALTER TABLE users ADD INDEX index_name (index_column)
Now add the constraint
ALTER TABLE foreign_key_table
ADD CONSTRAINT foreign_key_name FOREIGN KEY (foreign_key_column)
REFERENCES primary_key_table (primary_key_column) ON DELETE NO ACTION
ON UPDATE CASCADE;
Note if you don't add an index it wont work.
After battling with it for about 6 hours I came up with the solution
I hope this save a soul.
MySQL will execute this query:
ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Cheers!
When you add a foreign key constraint to a table using ALTER TABLE, remember to create the required indexes first.
Create index
Alter table
try all in one query
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0,
ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
step 1: run this script
SET FOREIGN_KEY_CHECKS=0;
step 2: add column
ALTER TABLE mileage_unit ADD COLUMN COMPANY_ID BIGINT(20) NOT NULL
step 3: add foreign key to the added column
ALTER TABLE mileage_unit
ADD FOREIGN KEY (COMPANY_ID) REFERENCES company_mst(COMPANY_ID);
step 4: run this script
SET FOREIGN_KEY_CHECKS=1;
ALTER TABLE child_table_name ADD FOREIGN KEY (child_table_column) REFERENCES parent_table_name(parent_table_column);
child_table_name is that table in which we want to add constraint.
child_table_column is that table column in which we want to add foreign key.
parent table is that table from which we want to take reference.
parent_table_column is column name of the parent table from which we take reference
this is basically happens because your tables are in two different charsets. as a example one table created in charset=utf-8 and other tables is created in CHARSET=latin1 so you want be able add foriegn key to these tables. use same charset in both tables then you will be able to add foriegn keys. error 1005 foriegn key constraint incorrectly formed can resolve from this
The foreign key constraint must be the same data type as the primary key in the reference table and column
ALTER TABLE TABLENAME ADD FOREIGN KEY (Column Name) REFERENCES TableName(column name)
Example:-
ALTER TABLE Department ADD FOREIGN KEY (EmployeeId) REFERENCES Employee(EmployeeId)
i geted through the same problem. I my case the table already have data and there were key in this table that was not present in the reference table. So i had to delete this rows that disrespect the constraints and everything worked.
Double check if the engine and charset of the both tables are the same.
If not, it will show this error.
I have a mysql database which have set of tables One table have a composite key as the primary key and and a single foreign key. Following are the table definitions.
CREATE TABLE IF NOT EXISTS `ohrm_emp_education` (
`emp_number` int(11) NOT NULL,
`education_id` int(11) NOT NULL,
`institute` varchar(100) DEFAULT NULL,
`major` varchar(100) DEFAULT NULL,
`year` decimal(4,0) DEFAULT NULL,
`score` varchar(25) DEFAULT NULL,
`start_date` date DEFAULT NULL,
`end_date` date DEFAULT NULL,
PRIMARY KEY (`emp_number`,`education_id`),
KEY `education_id` (`education_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `ohrm_emp_education`
ADD CONSTRAINT `ohrm_emp_education_ibfk_1` FOREIGN KEY (`emp_number`) REFERENCES `hs_hr_employee` (`emp_number`) ON DELETE CASCADE,
ADD CONSTRAINT `ohrm_emp_education_ibfk_2` FOREIGN KEY (`education_id`) REFERENCES `ohrm_education` (`id`) ON DELETE CASCADE;
But now I need to add a new column to this existing table and make it as the primary key. I tried it with the following query.
ALTER TABLE ohrm_emp_education
ADD column id int not null AUTO_INCREMENT,
DROP PRIMARY KEY,
ADD primary key (id)
But it shows following error
#1025 - Error on rename of './test/#sql-4f6_19b' to './test/ohrm_emp_education' (errno: 150)
I tried with several answers which are found on the internet but couldn't solve it properly. Can someone help me on this. Thanks in advance.
Try to delete foreign keys first, something like this:
ALTER TABLE `ohrm_emp_education` DROP FOREIGN KEY `emp_number`;
ALTER TABLE `ohrm_emp_education` DROP FOREIGN KEY `education_id`;
And then alter table.
If you are using SQL Server Management Studio.
Then right click on the table and click design.
Then right click on the row which contains the composite key
and click on remove primary key
then add new column
and insert data into that column
and check that the column has no empty data.
Then again go to design view
and right click on the required column and click on Set as Primary Key
You're Done!!
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
drop/disable foreign key constraint. Drop primary key, add new PK, enable/add fk.