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:
Related
The following create table sql code is not producing the expected results.
CREATE TABLE mentorships (
mentor_ID INT NOT NULL,
mentee_ID INT NOT NULL,
status VARCHAR(255) NOT NULL,
project VARCHAR(255) NOT NULL,
PRIMARY KEY (mentor_ID, mentee_ID, project),
CONSTRAINT fk1 FOREIGN KEY(mentor_ID) REFERENCES co_employees(id) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT fk2 FOREIGN KEY(mentee_ID) REFERENCES co_employees(id) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT mm_constraint UNIQUE(mentor_ID, mentee_ID));
After running the code, when I check the indexes for the new table in phpmyadmin, I expect to see an index for fk1 as well as the others listed in the screenshot below. But as you can see in the screenshot, there is no fk1 index showing up.
Any idea as to why the fk1 index is not showing up or why it hasn't been created?
To clarify the points made in the comments above, here's what it says in the manual:
https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html
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.
(emphasis mine)
The "referencing table" in your case is mentorships, the table in which you are defining the foreign keys.
This statement from the manual is consistent with the points Jon Armstrong was making: the primary key satisfies the index requirement for the foreign key on mentor_id because that's the first column in the primary key index. But it does not satisfy the index for the foreign key on mentee_id because that's not the first column. Therefore it had to create a new index only for mentee_id.
I created my tables in workbench and forward engineered to create my database. When I backed up my database by export/dump, I came across some lines of code for CREATE TABLE that I'm not sure why they look the way they do:
I have CONSTRAINT-FOREIGN KEY()REFERENCES-() for all my foreign key constraints which makes sense. But I also have KEY which seems to be creating an index for some of my foreign keys but not for all of them in many of my tables. I don't know what this KEY line does and why it's this way? In the example below, I have KEY for 2 of my 3 FKs (one of the FKs being a composite FK made up of 3).
After the KEY and CONSTRAINT, sometimes the code just mentions the foreign key name, and some other times it has the format fk_referencingTable_referencedTable1. Accidentally in this example the composite foreign key has this second format, but really it looks like any foreign key (either single or composite) can randomly have either one of these 2 formats? Why is that and should I be concerned about it?
DROP TABLE IF EXISTS `Recommendations`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Recommendations` (
`client_SIN` char(9) NOT NULL
`advisor_SIN` char(9) NOT NULL,
`exchange_name` varchar(45) NOT NULL,
`security_tradeName` varchar(45) NOT NULL,
`FSI_name` varchar(45) NOT NULL,
`Date` date DEFAULT NULL,
`Quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`client_SIN`,`advisor_SIN`,`exchange_name`,`security_tradeName`,
`FSI_name`),
KEY `advisor_SIN_idx` (`advisor_SIN`),
KEY `fk_Recommendations_Exchanges_has_Securities1_idx`
(`exchange_name`,`security_tradeName`,`FSI_name`),
CONSTRAINT `advisor_SIN` FOREIGN KEY (`advisor_SIN`)
REFERENCES `Advisors` (`advisor_SIN`)
ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `client_SIN` FOREIGN KEY (`client_SIN`)
REFERENCES `Clients` (`client_SIN`)
ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `fk_Recommendations_Exchanges_has_Securities1`
FOREIGN KEY (`exchange_name`, `security_tradeName`, `FSI_name`)
REFERENCES `Exchanges_has_Securities` (`Exchanges_exchange_name`,
`Securities_security_tradeName`, `Securities_issuer_name`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Creating a foreign key automatically adds a key for the column(s) in the FK if it's not already indexed. There's no additional KEY for client_SIN because it's the first column in the primary key, and any prefix of a composite index is an index of its own.
I believe the index names you got were assigned by MySQL Workbench. The default in MySQL is to use the first column name as the index name when you don't name an index explicitly. But it looks like MySQL Workbench appends _idx when it creates the index. And if it's creating the index for a foreign key it uses the prefix fk_ as well.
KEY is keyword-statement for index creation (i.e. it is sub-statement). It creates an index, changing the data storage.
FOREIGN KEY is a keyword-rule (yes, this is one keyword despite it consist from two separate words) for consistency checking subsystem, and does not cause any change in data storage itself. But it contains hidden statements - first of them checks does the index where the reference expression is a prefix exists, second creates an index by this expression if the checking fails (i.e. second hidden statement is KEY statement). CONSTRAINT is naming part of FOREIGN KEY rule (if it is absent then the name will be generated automatically).
Why does Mysql/InnoDB seem to rename some of the foreign keys I create?
e.g.
mysql> alter table JOB_LISTENER add foreign key FK_JOBS (job_id) REFERENCES job(id);
mysql>
mysql> show create table JOB_LISTENER;
snip> ....
mysql> CONSTRAINT `JOB_LISTENER_ibfk_4` FOREIGN KEY (job_id) REFERENCES job (id)
snip> ....
it renames the foreign key i created named FK_JOBS to JOB_LISTENER_ibfk_4 - any ideas why it does that?
Many thanks,
Sean
You must use the CONSTRAINT keyword to name a constraint:
mysql> ALTER TABLE JOB_LISTENER ADD CONSTRAINT FK_JOBS FOREIGN KEY (job_id)
REFERENCES job(id);
This automatically names the index to the same name, if it needs to create an index.
mysql> SHOW CREATE TABLE JOB_LISTENER\G
*************************** 1. row ***************************
Table: JOB_LISTENER
Create Table: CREATE TABLE `JOB_LISTENER` (
`job_id` int(11) DEFAULT NULL,
KEY `FK_JOBS` (`job_id`),
CONSTRAINT `FK_JOBS` FOREIGN KEY (`job_id`) REFERENCES `job` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html says:
If the CONSTRAINT symbol clause is given, the symbol value, if used, must be unique in the database. A duplicate symbol will result in an error similar to: ERROR 1022 (2300): Can't write; duplicate key in table '#sql- 464_1'. If the clause is not given, or a symbol is not included following the CONSTRAINT keyword, a name for the constraint is created automatically.
Sometimes you have to read between the lines. In the above paragraph, I infer from the last sentence that you must use the CONSTRAINT keyword to give a name for the constraint, because if you don't, then the constraint name is created automatically.
Tip: Be aware that constraint names must be unique within the database, not only within the table. Go figure, this is part of the SQL standard. So you may not expect this, so be careful not to use duplicate constraint names.
Whereas in some implementations you can use the same index name in multiple tables in the same database (the SQL standard does not cover index implementation, as a_horse_with_no_name reminds me).
I was creating a database and I want to make relation between tables "Member" and "Group_Member". But when I make the column "Memp_Id" as a foreign Key in table "Group_Member" as the picture shown this error appear.
I have checked the data type but both are the same. What I have to do now?
Reasons for error code 1215 cannot add foreign key constraint are listed in percona's article, but in the most cases the reasons are as follows:
child table's potential foreign key contains ids which is not present in parent table, but
your child table 'Group_Member' is empty so it is not applicable for
you.
The Local Key, Foreign Table or Column in the Constraint References
Have a Typo
The Column the Constraint Refers to Is Not of the Same Type or Width
as the Foreign Column, for e.g.if primary key has data type and width int(11) then foreign key's type and width also has to be as int(11)
Different Charsets/Collations Among the Two Table/Columns, for example if primary key has collation utf8_unicode_ci and foreign key has collation as latin1_general_ci then error will occur, so it should be the same.
The Parent Table Is Not Using InnoDB, for setting foreign key, if your parent table is of type MyISAM then it will show above error #1252 so it should be InnoDB.
The Parent Table Is Partitioned, you should check partition also.
Using SET DEFAULT for a Constraint Action, like Default NULL on PK or FK so Dont use Default on these keys.
Make sure they are both the same datatype and check if unsigned is the same on both, and that if you already have group_member rows then mem_id values will need to exist in the members table.
See here for more clarity of what unsigned means,
What does "unsigned" in MySQL mean and when to use it?
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.