In have a many-to-many linking table and I'm trying to set up two foreign keys on it. I run these two statements:
ALTER TABLE address_list_memberships
ADD CONSTRAINT fk_address_list_memberships_address_id
FOREIGN KEY index_address_id (address_id)
REFERENCES addresses (id);
ALTER TABLE address_list_memberships
ADD CONSTRAINT fk_address_list_memberships_list_id
FOREIGN KEY index_list_id (list_id)
REFERENCES lists (id);
I would expect that when I run SHOW CREATE TABLE address_list_memberships I'd see this:
[...]
KEY `index_address_id` (`address_id`),
KEY `index_list_id` (`list_id`),
CONSTRAINT `fk_address_list_memberships_list_id` FOREIGN KEY (`list_id`)
REFERENCES `lists` (`id`),
CONSTRAINT `fk_address_list_memberships_address_id` FOREIGN KEY (`address_id`)
REFERENCES `addresses` (`id`)
But instead I get this:
[...]
KEY `index_list_id` (`list_id`),
CONSTRAINT `fk_address_list_memberships_list_id` FOREIGN KEY (`list_id`)
REFERENCES `lists` (`id`),
CONSTRAINT `fk_address_list_memberships_address_id` FOREIGN KEY (`address_id`)
REFERENCES `addresses` (`id`)
It looks as though only one index is there. Seems to contradict the MySQL docs which say MySQL automatically creates an index on the referencing column whenever you create a foreign key.
I've noticed this only-one-index thing every time I create two FKs on a table whether I use a GUI tool such as CocoaMySQL or SQLyog, or whether I do it on the command line.
Any illumination of this mystery would be very much appreciated.
I just tried it and it works fine for me. I copied and pasted the ALTER statements you wrote and here is what I get:
mysql> show create table address_list_memberships;
CREATE TABLE `address_list_memberships` (
`address_id` bigint(20) unsigned NOT NULL,
`list_id` bigint(20) unsigned NOT NULL,
KEY `index_address_id` (`address_id`),
KEY `index_list_id` (`list_id`),
CONSTRAINT `fk_address_list_memberships_list_id`
FOREIGN KEY (`list_id`) REFERENCES `lists` (`id`),
CONSTRAINT `fk_address_list_memberships_address_id`
FOREIGN KEY (`address_id`) REFERENCES `addresses` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I'm using MySQL 5.0.51a on Mac OS X.
edit: Try the following query to get all the indexes MySQL thinks exist on your table:
SELECT * FROM information_schema.key_column_usage
WHERE table_schema = 'test' AND table_name = 'address_list_memberships'\G
(I used the 'test' database for my test; you should replace this string with the name of the schema where your table is defined.)
It doesn't really matter. You still have an index on list_id. MySQL requires any foreign key constraint to also have an index on the referencing fields. Since both index_list_id and fk_address_list_memberships_list_id are built on list_id, MySQL probably sees this and uses index_list_id as the index, renaming it to fk_address_list_memberships_list_id. You could even skip declaring the index, since MySQL will do it implicitly in the version you are using.
Related
I cannot seem to be able to delete primary keys in a table.
All references (FKs) have been removed but it still doesn't let me delete it.
What I'm trying to do is: delete old primary keys to add a new one - but keep the old columns and data (just remove the PK attribute).
What is wrong ?
Table:
CREATE TABLE `employee` (
`User` int(10) unsigned NOT NULL,
`Company` int(10) unsigned NOT NULL,
--unrelated boolean fields
PRIMARY KEY (`User`,`Company`),
KEY `FK_Employee_Company_idx` (`Company`),
CONSTRAINT `FK_Employee_Company` FOREIGN KEY (`Company`) REFERENCES `company` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_Employee_User` FOREIGN KEY (`User`) REFERENCES `user` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Trying to delete:
alter table Employee
drop primary key;
Issue:
Error 1025: Error on rename of '.\DB_NAME#sql-3640_4' to '.\DB_NAME\employee' (errno: 150 "Foreign key constraint is incorrectly formed") SQL Statement: ALTER TABLE DB_NAME.employee DROP PRIMARY KEY
Nothing references this table anymore. I also checked via statements which select from information_schema.key_column_usage but yields no results.
Wasted the last hours on Google but can't seem to figure it out.
And if that would work, adding a new column:
alter table Employee
add column ID int unsigned not null auto_increment primary key;
The index is still needed for the existing FK constraints.
Adding the following index (first) should satisfy that requirement:
CREATE INDEX xxx ON employee (User, Company);
Test case
I thought I had foreign keys setup on my tables, but despite having the correct syntax in my DDL, and even when attempting to add a constraint after the fact, nothing happens. I do not get any errors, and I get a message saying '10 row(s) affected Records: 10 Duplicates: 0 Warnings: 0'
Here is the definition for my table:
CREATE TABLE USERS_COURSES (
USERS_COURSES_ID INT NOT NULL AUTO_INCREMENT,
USER_ID INT NOT NULL,
COURSE_ID INT NOT NULL,
ROLE INT NOT NULL,
CONSTRAINT PK_USERS_COURSES PRIMARY KEY (USERS_COURSES_ID),
CONSTRAINT U_USERS_COURSES UNIQUE (USER_ID, COURSE_ID),
CONSTRAINT FK_USERS_COURSES_USERS FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID),
CONSTRAINT FK_USERS_COURSES_COURSES FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
);
When I look at the table in MySQL Workbench, and via IntelliJ IDEA, all I see is a single index called FK_USERS_COURSES_COURSES (COURSE_ID)
I can run the following commands as many times as I like, and apparnetly nothing happens:
ALTER TABLE USERS_COURSES ADD CONSTRAINT FK_USERS_COURSES_USERS FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID);
ALTER TABLE USERS_COURSES ADD CONSTRAINT FK_USERS_COURSES_COURSES FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID);
Here is what I see in my Database tab in IntelliJ:
What might be causing this? I need the foreign keys to prevent deletions, and right now this is not happening.
Check out the InnoDB documentation for MySQL.
While MySQL accepts foreign key declarations as valid syntax, at present only the InnoDB engine actually implements them. If it's not the default on your setup, include it in the table options - CREATE TABLE...ENGINE=InnoDB
MySQL 5.6.16
Two tables. Altering Table 1 to have a foreign key to Table 2's primary key. SQL Error 1215.
If I drop Table 1 and incorporate the foreign key constraint into the build, it accepts the constraint just fine. Only altering the tables after creation causes a problem.
Any ideas? Below are two attempts at writing the alter statement, followed by the creation script.
ALTER TABLE c_users ADD FOREIGN KEY fk_user_prof_position_tid(professional_position_tid) REFERENCES d_taxonomy(tid);
ALTER TABLE c_users ADD CONSTRAINT fk_user_prof_position_tid FOREIGN KEY (professional_position_tid) REFERENCES d_taxonomy(tid);
CREATE TABLE c_users (
user_id INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary, auto-generated key',
professional_position_tid INT(11),
...
PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE INDEX i_user_id ON c_users (user_id) USING BTREE;
CREATE TABLE d_taxonimy (
tid INT(11) NOT NULL COMMENT '',
...
PRIMARY KEY (tid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE INDEX i_tid ON d_taxonimy (tid) USING BTREE;
Typos:
ALTER TABLE [...snip...] REFERENCES d_taxonomy(tid);
^----
CREATE TABLE d_taxonimy (
^----
Plus, if you're running the statements in that order, you can't alter a table which doesn't exist yet, or create a foreign key when the foreign field/table don't exist yet either.
I create a table in mysql using the following script:
CREATE TABLE IF NOT EXISTS users_x_activities(
id int NOT NULL auto_increment,
id_user int unsigned NOT NULL,
id_attivita int unsigned NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (id_user) REFERENCES utente(id),
FOREIGN KEY (id_attivita) REFERENCES attivita(id)
) ENGINE = INNODB;
When I export the created table from phpMyAdmin, I obtain the following script
CREATE TABLE IF NOT EXISTS `users_x_activities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(10) unsigned NOT NULL,
`id_attivita` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `id_user` (`id_user`),
KEY `id_attivita` (`id_attivita`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
So the question are: where is my foreign key constraints? does KEY refer to FK? Seems that the two tables utente and attivita are no longer referenced in the new generated script. where am I doing wrong?
EDIT
In phpMyAdmin, configuring the export of the table I found the option "Display Foreign Key Relationship"
If I flag this option I otain also this code in the script
--
-- RELATIONS FOR TABLE `users_x_activity`:
-- `id_user`
-- `utente` -> `id`
-- `id_attivita`
-- `attivita` -> `id`
--
--
-- Constraints for dumped tables
--
--
-- Constraints for table `users_x_activity`
--
ALTER TABLE `users_x_activity`
ADD CONSTRAINT `users_x_activities_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `utente` (`id`),
ADD CONSTRAINT `users_x_activities_ibfk_2` FOREIGN KEY (`id_attivita`) REFERENCES `attivita` (`id`);
This means that if I add the option "Display Foreign Key Relationship" I obtain also the FK constrains? in other case not?
So the question are: where is my foreign key constraints?
They are defined in the database. The output from SHOW CREATE TABLE users_x_activities will include the foreign key constraint definitions.
The definitions of the foreign key constraints likely appear in separate ALTER TABLE statements at the end of the generated script.
does KEY refer to FK?
No. KEY id_user (id_user) here refers to an index.
Seems that the two tables utente and attivita are no longer referenced in the new generated script.
Yes, you are correct. The foreign key constraints are not included in the CREATE TABLE statement.
where am I doing wrong?
A MySQL SHOW CREATE TABLE users_x_activities will include the foreign key constraints.
The foreign key constraints are likely included in the script generated by phpMyAdmin, but at the end of the script, in separate ALTER TABLE statements.
There are two type of constraints when you managing your tables with phpmyadmin:
internal: when you set constraints with phpmyadmin designer for example the constraints stored as internal,that will not be included in export.
innoDB: these constraints included in export check out linked video about it
Setting up a foreign key constraint
Follow the following steps :
phpmyadmin configuration
export time customer configuration
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.