I have a table whose primary key I'm trying to change.
this is the table definition.
CREATE TABLE `tbl_customer` (
`PersonId` int(11) NOT NULL,
`Id` int(10) unsigned NOT NULL,
`Name` varchar(100) collate utf8_spanish_ci NOT NULL,
`Alias` varchar(50) collate utf8_spanish_ci NOT NULL,
`Phone` varchar(30) collate utf8_spanish_ci default NULL,
`Phone2` varchar(30) collate utf8_spanish_ci default NULL,
`Email` varchar(50) collate utf8_spanish_ci default NULL,
`Email2` varchar(50) collate utf8_spanish_ci default NULL,
`RFC` varchar(13) collate utf8_spanish_ci default NULL,
`AddressStreetName` varchar(45) collate utf8_spanish_ci default NULL,
`AddressStreetNumber` varchar(45) collate utf8_spanish_ci default NULL,
`AddressCityWard` varchar(45) collate utf8_spanish_ci default NULL,
`AddressCityName` varchar(45) collate utf8_spanish_ci default NULL,
`AddressStateName` varchar(45) collate utf8_spanish_ci default NULL,
`AddressCountryName` varchar(45) collate utf8_spanish_ci default NULL,
`AddressPostalCode` int(10) default NULL,
`IsDistributor` tinyint(1) NOT NULL default '0' COMMENT '1 = Is Distributor, 0 = Is Not Distributor',
`ParentCustomerId` int(10) NOT NULL default '11' COMMENT 'Our Id is 11, so by default, all customers right now are our children.',
PRIMARY KEY (`Id`),
KEY `fk_tbl_cliente_tbl_cliente1_idx` (`ParentCustomerId`),
KEY `fk_tbl_cliente_tbl_person1_idx` (`PersonId`),
KEY `PersonId` (`PersonId`),
KEY `PersonId_2` (`PersonId`),
CONSTRAINT `fk_tbl_cliente_tbl_cliente1` FOREIGN KEY (`ParentCustomerId`) REFERENCES `tbl_customer` (`PersonId`),
CONSTRAINT `fk_tbl_cliente_tbl_person1` FOREIGN KEY (`PersonId`) REFERENCES `zapata`.`tbl_person` (`Id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci COMMENT='''Customer'' refers to a person or entity to which we provide '$$
Now, when I first tried to:
ALTER TABLE `tbl_customer` DROP PRIMARY KEY;
My PRIMARY KEY is Id . When I tried to drop it I got..
Error Code: 1025. Error on rename of './services/#sql-29a_218cc7f' to './services/tbl_customer' (errno: 150)
So, I deleted all FOREIGN KEY constraints that referred to this table and column, and still got the same error. I also went over to SHOW ENGINE INNODB STATUS And found out this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
130226 14:41:11 Error in foreign key constraint of table services/tbl_employee_shift:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match to the ones in table. Constraint:
,
CONSTRAINT fk_tbl_employee_shift_tbl_customer1 FOREIGN KEY (CustomerId) REFERENCES services.tbl_customer (Id) ON UPDATE CASCADE
However, the table services.tbl_employee_shift does not exist (it existed once but it was dropped several weeks before I tried this change). So I went on and...
CREATE TABLE services.tbl_employee_shift(
CustomerId INT (11)
);
ALTER TABLE services.tbl_employee_shift ADD CONSTRAINT fk_tbl_employee_shift_tbl_customer1 FOREIGN KEY (CustomerId) REFERENCES avatar.tbl_cliente (Id);
ALTER TABLE services.tbl_employee_shift DROP FOREIGN KEY fk_tbl_employee_shift_tbl_customer1;
And it works... but it doesn't correct the necessary information, seemingly InnoDB still believes that the constraint fk_tbl_employee_shift_tbl_customer1 is alive and thus, is 'preventing the drop of the primary key to keep consistency'...
I'm using MySQL 5.0.95.
EDIT: This problem went unresolved, it was worked around
The problem could only be corrected when we migrated the database to a newer server (same mysql version), seems like there was a broken/ghost reference to a ghost foreign key (fk_tbl_employee_shift_tbl_customer1 ) which prevented the column from being dropped. Since this broken/ghostfk wasn't in the new server, I could drop the column with no problems then. My guess is it was a bug, but unfortunately I can't recreate it.
It sounds as though you dropped tbl_employee_shift whilst foreign_key_checks was set to 0:
Setting foreign_key_checks to 0 also affects data definition statements: DROP SCHEMA drops a schema even if it contains tables that have foreign keys that are referred to by tables outside the schema, and DROP TABLE drops tables that have foreign keys that are referred to by other tables.
Since this behaviour is documented, it must be considered by-design and therefore not a bug.
The error occurs when foreign key is bad formulated.
the SQL is correct, i run script in my localhost, i get same error.
the solution is verify that table tbl_person was created with engine "InnoDB".
greetings
Just dealt with this problem today. There was no sign of the two affected tables in any of the schema information tables. I searched the various system databases looking for the FK, to no avail. In the end, dropping the database worked instantly.
I had a similar error, what mysql requires is that you have both key and foreign, type and size match,
for eg. person.id int (10) must mapped to service_customer.person_id in (10)
if the type and size differ, mysql will complain.
Related
I got the following error message whenever I try to import this sql file to my localhost
(#1005 - Can't create table hostel_management_system.Hostel_Manager (errno: 150 "Foreign key constraint is incorrectly formed"))
Here is the sql:
DROP TABLE IF EXISTS `Hostel_Manager`;
CREATE TABLE `Hostel_Manager` (
`Hostel_man_id` int(10) NOT NULL AUTO_INCREMENT,
`Username` varchar(255) NOT NULL,
`Fname` varchar(255) NOT NULL,
`Lname` varchar(255) NOT NULL,
`Mob_no` varchar(255) NOT NULL,
`Hostel_id` int(10) NOT NULL,
`Pwd` LONGTEXT NOT NULL,
`Isadmin` tinyint(1) DEFAULT '0',
PRIMARY KEY (`Hostel_man_id`),
UNIQUE (`Username`),
KEY `Hostel_id` (`Hostel_id`),
CONSTRAINT `Hostel_Manager_ibfk_1` FOREIGN KEY (`Hostel_id`) REFERENCES `Hostel` (`Hostel_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
LOCK TABLES `Hostel_Manager` WRITE;
UNLOCK TABLES;
Hostel table :
CREATE TABLE `Hostel` (
`Hostel_id` int(10) NOT NULL AUTO_INCREMENT,
`Hostel_name` varchar(255) NOT NULL,
`current_no_of_rooms` varchar(255) DEFAULT NULL,
`No_of_rooms` varchar(255) DEFAULT NULL,
`No_of_students` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Hostel_id`)
)
Why do I get that error and how to fix it?
Both the parent and children column have the same datatype and length, and the parent column is a primary colum, so that's not the issue here.
I suspect that the problem is the charset. Hostel_Manager specifies a default charset, while Hostel does not. If the default charset of your database is something else than latin1, then the foreign is malformed.
I would recommend explictly aligning the charset so it is the same for both tables (either remove both, or declare the same value).
Note that both tables also need to have the same storage engine. InnoDB is the default, so that should not be an issue, but you might want to explictly align that as well (in case the default of your database is MyISAM).
I'm trying to set up two tables in a database, and add a foreign key between them. They're declared as follows:
CREATE TABLE `clothing` (
`name` varchar(26) COLLATE utf8_bin NOT NULL,
`image` varchar(64) COLLATE utf8_bin NOT NULL,
`localized_name` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`localized_name`)),
`main` varchar(18) COLLATE utf8_bin DEFAULT NULL,
`stars` tinyint(3) unsigned NOT NULL,
`id` tinyint(3) unsigned NOT NULL,
`splatnet` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`splatnet`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `abilities` (
`name` varchar(18) COLLATE utf8_bin DEFAULT NULL,
`image` varchar(48) COLLATE utf8_bin NOT NULL,
`id` tinyint(3) unsigned NOT NULL,
`localized_name` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`localized_name`))
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
I want to create a foreign key on clothing that references abilities with the following command:
ALTER TABLE `abilities` ADD FOREIGN KEY (`name`) REFERENCES `clothing` (`main`);
However, attempting to do this raises this error in return:
Source and target columns must have the same data type, there must be an index on the target columns and referenced data must exist.
Can't create table `prismarine_rusted`.`abilities` (errno: 150 "Foreign key constraint is incorrectly formed")
I'm not entirely sure what's causing this, and unless I'm overlooking something really obvious, main and name have the same type, and therefore, should be able to be tied together via a foreign key. I'm using MariaDB v10.4.12, with SQL mode set to TRADITIONAL.
Although the foreign and primary key columns involved here are the same type, you are trying to reference clothing.main, which is not a unique or primary key column. From the MariaDB documentation:
The referenced columns must be a PRIMARY KEY or a UNIQUE index.
Note that this differs from InnoDB on MySQL, where a foreign key column can in fact reference a non unique column in another table.
One way to remedy this error would be to make clothing.main a unique column:
ALTER TABLE clothing ADD UNIQUE (main);
Note that doing this might only make logical sense if the values in main are already unique. If not, then perhaps you would have to revisit your data model.
It might be because there is a value in abilities.name that has no match in the referenced table.
This is my first table.
CREATE TABLE `raw_orders` (
`row_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`order_id` VARCHAR(45) COLLATE utf8mb4_unicode_ci NOT NULL,
`order_revenue` FLOAT NOT NULL,
PRIMARY KEY(`row_id`),
KEY(`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ciÍž
This is my second table
CREATE TABLE `formatted_orders` (
`order_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`client_order_id` VARCHAR(50) COLLATE utf8mb4_general_ci NOT NULL,
`order_revenue` FLOAT NOT NULL,
PRIMARY KEY(`order_id`),
KEY(`client_order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ciÍž
I am trying to add foreign key in formatted_orders linking it to raw_orders by using this
ALTER TABLE formatted_orders
ADD FOREIGN KEY (client_order_id) REFERENCES raw_orders(order_id);
But I get this error
ERROR (HY000): Cannot add foreign key constraint
You can simply add a foreign key in the table formatted_orders like this:
CREATE TABLE `formatted_orders` (
`order_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`client_order_id` VARCHAR(50) COLLATE utf8mb4_general_ci NOT NULL,
`order_revenue` FLOAT NOT NULL,
PRIMARY KEY(`order_id`),
FOREIGN KEY (`client_order`) REFERENCES raw_orders(`order_id`)
)
The reason you cannot add the constraint is because you specify different collations for the columns in the two tables. Also, the columns should be the same size, although MySQL will let you create the constraint even if they're not.
Change to the same collation (COLLATE utf8mb4_unicode_ci for instance) for both columns and it will work.
See this SQL Fiddle for an example.
The MySQL documentation states that:
Corresponding columns in the foreign key and the referenced key must
have similar data types. The size and sign of integer types must be
the same. The length of string types need not be the same. For
nonbinary (character) string columns, the character set and collation
must be the same.
I got two tables, first one with some peoples' data, and second with some codes.
What I want to do is set FK to make DB to check if new person data contains a "code" from the list from the second table. Both tables got PK on codes column, but I still receive error.
ERROR 1215: Cannot add foreign key constraint
SQL Statement:
ALTER TABLE `MYBASE`.`first_table`
ADD CONSTRAINT `fk_new_fkey`
FOREIGN KEY (`code_indentyfication`)
REFERENCES `MYBASE`.`second_table` (`codes`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'first_table' already exists
SQL Statement:
CREATE TABLE `first_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code_indentyfication` varchar(2) COLLATE utf8_polish_ci NOT NULL,
`number_identyfication` varchar(45) COLLATE utf8_polish_ci NOT NULL,
`name` varchar(45) COLLATE utf8_polish_ci DEFAULT NULL,
`surname` varchar(45) COLLATE utf8_polish_ci DEFAULT NULL,
`adress` varchar(45) COLLATE utf8_polish_ci DEFAULT NULL,
PRIMARY KEY (`id`,`code_indentyfication`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci
Codes are varchar(2) and I would like to set FK without making any change in columns set.
Any ideas?
I am using MySQL server, and this code was generated by MySQL Workbench if that helps.
Try that:
ALTER TABLE `MYBASE`.`first_table`
ADD FOREIGN KEY (`code_indentyfication`)
REFERENCES `MYBASE`.`second_table` (`codes`);
I'm trying to add foreign keys to my two tables Problem and File.
These are the CREATE queries.
And both tables are created successfully:
CREATE TABLE lpsolve.tbl_file (
id INT(11) NOT NULL AUTO_INCREMENT,
problem_id INT(11) DEFAULT NULL,
title VARCHAR(255) DEFAULT NULL,
description VARCHAR(255) DEFAULT NULL,
type VARCHAR(255) DEFAULT NULL,
create_time DATETIME DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB
AUTO_INCREMENT = 1
CHARACTER SET latin1
COLLATE latin1_swedish_ci;
CREATE TABLE lpsolve.tbl_probem (
id INT(11) NOT NULL AUTO_INCREMENT,
title VARCHAR(255) DEFAULT NULL,
description VARCHAR(255) DEFAULT NULL,
create_time DATETIME DEFAULT NULL,
number_of_files INT(11) DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB
AUTO_INCREMENT = 1
CHARACTER SET latin1
COLLATE latin1_swedish_ci;
But when I try to add the following constraint I get the Error 1215 Error. This is the add constraint query:
ALTER TABLE tbl_file
ADD CONSTRAINT fk_problem_file
FOREIGN KEY (problem_id)
REFERENCES tbl_problem(id)
ON DELETE CASCADE
ON UPDATE RESTRICT
The query does not work even by removing the ON DELETE CASCADE and ON UPDATE RESTRICT either. There are a couple of similar problems mentioned in Stack Overflow but they did not answer my problem unfortunately.
Error message:
Cannot add foreign key constraint
The table name is tbl_probem
CREATE TABLE lpsolve.tbl_probem (
but the ALTER command is trying to reference a table:tbl_problem
REFERENCES tbl_problem(id)
Delete l from problem to solve this problem.