Failure in using alter table to add partition - mysql

I have a table having structure as below:
CREATE TABLE `child_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`value` int,
`ref_id` int,
PRIMARY KEY (`id`),
KEY `ref_id` (`ref_id`),
CONSTRAINT `FK4E9BF08E940F8C98` FOREIGN KEY (`ref_id`) REFERENCES `parent_table` (`id`) ON DELETE CASCADE
)
When running statement to add partition, it fails and show the error:
ERROR 1217: Cannot delete or update a parent row: a foreign key constraint fails
SQL Statement:
ALTER TABLE `learning`.`child_table` PARTITION BY HASH(ref_id) PARTITIONS 10
So I remove the foreign constraint with parent_table, then run again. It still fails and show the same error.
Did I do anything wrong?

I know this is an old question, but for people that fall here from looking for this problem, since its the first Google result:
MySQL does not support foreign keys on partitioned tables.
From the manual
Foreign keys not supported for partitioned InnoDB tables. Partitioned tables using the InnoDB storage engine do not support foreign keys. More specifically, this means that the following two statements are true:
No definition of an InnoDB table employing user-defined partitioning may contain foreign key references; no InnoDB table whose definition contains foreign key references may be partitioned.
No InnoDB table definition may contain a foreign key reference to a user-partitioned table; no InnoDB table with user-defined partitioning may contain columns referenced by foreign keys.

The error is referring to a foreign key on another table that references child_table. You need to find and remove the foreign key from that table, not necessarily child_table. You could also try running SET foreign_key_checks = 0 first.

Related

purpose of declaring foreign keys in mysql MyISAM engine

I just came to know that mysql MyISAM engine doesn't support foreign keys.But i have seen several example of declaring foreign keys like below :
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
As foreign keys are not supported we would not get the benefits like on update and on delete in MyISAM engine.My question is then why we are declaring a field as foreign key in MyISAM engine ?
There is no point of declaring foreign keys with the myisam table type, since this functionality does not exist there. Mysql can parse the foreign key syntax for the myisam table type (meaning no error message will be raised if it encounters an fk definition), making migration from other database products or table engines easier because you do not have to edit the create table statements to remove them.

SQL Error (1215): Cannot add foreign key constraint

CREATE TABLE `profilePic` (
`ClientID` VARCHAR(255) NOT NULL,
PRIMARY KEY (`ClientID`),
CONSTRAINT `FK__user_details` FOREIGN KEY (`ClientID`) REFERENCES `user_details` (`ClientID`) ON UPDATE CASCADE ON DELETE CASCADE
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;
I am trying to add table with foreign key and I got this error, why that happend ?
trying doing new table.
i am trying to put same details on user_details->ClientID and profilePic->ClientID
3.i have already one table call`d userdb and in this table i have ClientID and its foreign key and its work.
The below will fail because the collation is different. Why do I show this? Because the OP didn't.
Note I shrunk the size due to error 1071 on sizing for varchar 255 with that collation and then auto chosen charset.
The point being, if collation is different, it won't work.
CREATE TABLE `user_details` (
`ClientID` VARCHAR(100) NOT NULL,
PRIMARY KEY (`ClientID`)
)ENGINE=InnoDB;
CREATE TABLE `profilePic` (
`ClientID` VARCHAR(100) NOT NULL,
PRIMARY KEY (`ClientID`),
CONSTRAINT `FK__user_details` FOREIGN KEY (`ClientID`) REFERENCES `user_details` (`ClientID`) ON UPDATE CASCADE ON DELETE CASCADE
)COLLATE='utf8mb4_unicode_ci' ENGINE=InnoDB;
The above failure is at the table level. A trickier one causing a 1215 error due to column-level collation mismatches can be seen in This answer.
Pulling the discussion up to more general cases ...
whether you are trying to establish a Foreign Key constraint on table creation or with ALTER TABLE
| ADD [CONSTRAINT [symbol]]
FOREIGN KEY [index_name] (index_col_name,...)
reference_definition
such as
ALTER TABLE `facility` ADD CONSTRAINT `fkZipcode`
FOREIGN KEY (`zipcode`) REFERENCES `allzips`(`zipcode`);
the following will apply.
From the MySQL manual page entitled Using FOREIGN KEY Constraints:
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.
In addition, the referenced (parent) table must have a left-most key available for fast lookup (verification). That parent key does not need to be PRIMARY or even UNIQUE. This concept is described in the 2nd chunk below. The first chunk alludes to a Helper index that will be created if necessary in the referencing (child) table if so necessary.
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.
InnoDB permits a foreign key to reference any 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.
When trying to create a foreign key via HeidiSQL, you get a warning as soon as the selected column data types don't match. I added this warning to HeidiSQL's table designer due to the non-intuitive message from the server ("Cannot add foreign key constraint")
The selected foreign column do not match the source columns data type and unsigned flag. This will give you an error message when trying to save this change. Please compare yourself:

MySQL - indexing innodb foreign keys

Is there an improvement in performance in indexing foreign keys in InnoDB? As far as I have read, InnoDB automatically creates an index for the foreign key.
Here is the query given to me for creating the table.
DROP TABLE IF EXISTS `assignments`;
CREATE TABLE `assignments`
(
`id` INTEGER NOT NULL AUTO_INCREMENT,
`user` INTEGER NOT NULL,
`job` INTEGER NOT NULL,
`created_at` DATETIME,
`updated_at` DATETIME,
PRIMARY KEY (`id`),
INDEX `job_fk1` (`user`),
INDEX `job_fk2` (`job`),
CONSTRAINT `job_fk1`
FOREIGN KEY (`user`)
REFERENCES `users` (`id`),
CONSTRAINT `job_fk2`
FOREIGN KEY (`job`)
REFERENCES `jobs` (`id`)
) ENGINE=InnoDB;
In there, he created foreign keys named job_fk1 and job_fk2. He used the names of these foreign keys as the name of the index.
Is there an improvement in performance in indexing foreign keys in InnoDB?
Answer: No. Performance will be degraded due to duplicate keys.
You do not need
INDEX `job_fk1` (`user`),
INDEX `job_fk2` (`job`),
Those will be automatically created by InnoDB internally. But you need to have index on users (id) and jobs (id) for faster operations on assignments table
http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
"InnoDB 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 is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.) index_name, if given, is used as described previously."
You are correct that MySQL will create an index on a column, if it doesn't already exist, when creating a foreign key constraint. However, feel free to create an index on the column and remove the auto-generated one if you want.
You also might want additional multi-column indexes to aid queries like this make-believe one:
SELECT id, user, job
FROM assignments
WHERE job = 5
ORDER BY user
The multi-column index (job, user) would satisfy both the search and the sort, and since secondary indexes include the primary key, it would also act as a covering index in this case.

Supports transactions, row-level locking, and foreign keys

For some reason I cannot create this table:
CREATE TABLE user_role (
user_id VARCHAR(20) NOT NULL,
role_id INTEGER UNSIGNED NOT NULL,
FOREIGN KEY (user_id)
REFERENCES users(user_id),
FOREIGN KEY (role_id)
REFERENCES roles(role_id)
);
The following similar table has no problems:
CREATE TABLE role_perm (
role_id INTEGER UNSIGNED NOT NULL,
perm_id INTEGER UNSIGNED NOT NULL,
FOREIGN KEY (role_id)
REFERENCES roles(role_id),
FOREIGN KEY (perm_id)
REFERENCES permissions(perm_id)
);
The error message I'm getting is:
#1005 - Can't create table 'test.user_role' (errno: 150) (Details...)
Supports transactions, row-level locking, and foreign keys
Any ideas?
See http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed.
If is rather difficult to guess as you didn't provide the definitions for the roles and permissions tables but to paraphrase the doc...
...in order to have a foreign key on a column, you must have an index on the "target" column.
...in order to have a foreign key on a column, both "source" and "target" columns must have the same type (incl. the same size if applicable).
...in order to have a foreign key on a column, both tables must use InnoDB engine.
For my case, I handle several databases, when I try to create the table it returned this error "transactions, row-level locking, and foreign keys", the error occurred because the relationship table did not exist,
casually it recognized it from another database where the table did exist, but i have only creating the relationship table to solve the problem.
I took into account the recommendations of relations given in this forum because it also has to do with the version of MySql.

Can't add Foreign Key in MySQL with identical columns

I have two tables, each with a provider column:
CREATE TABLE `title` (
`provider` varchar(40) CHARACTER SET latin1 NOT NULL,
CREATE TABLE `notification` (
`provider` varchar(40) CHARACTER SET latin1 NOT NULL,
However, when I try and add a foreign key
ALTER TABLE notification ADD FOREIGN KEY (provider) REFERENCES title (provider)
I get the following obscure error:
Can't create table 'metadata.#sql-c91_345b' (errno: 150)
Both of the tables are empty. Why is this occurring and what do I need to do to fix this?
http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html says:
InnoDB 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 is in contrast to some older versions, in which indexes had to
be created explicitly or the creation of foreign key constraints would
fail.) index_name, if given, is used as described previously.
I think you should create any (unique, primary, or plain) index for title.provider before creating a foreign key pointing to it.
Run SHOW ENGINE INNODB STATUS\G and look at the "LATEST FOREIGN KEY ERROR" to see more details on the error.