Mysql Foreign Key Creation - mysql

I am trying to add foreign key to my table with this script:
ALTER TABLE PRM_CTY
ADD CONSTRAINT fk_PRM_CTY_PRNT_CTY
FOREIGN KEY (PRNT_CTY_ID)
REFERENCES PRM_CTY(ID);
this code work but foreign key doesnt creat. instead of this a new index is created named fk_PRM_CTY_PRNT_CTY.
my foreign key returns an index
help me why it happens?

MySQL automatically creates an index to support each foreign key constraint, unless a suitable one already exists. The creation of an index suggests -- but does not prove -- that the constraint was successfully created. It is not a sign that constraint creation failed. To verify that the constraint exists, try to insert a row that violates it.
Edited to add:
Note, too, that you should be using the InnoDB storage engine if you want enforcement of foreign key constraints. The default default was MyISAM prior to MySQL 5.5, and that engine is still available, so if you were not aware of this issue then that could be what you are using.

Related

Whenever I try to set foreign key constraint to "NO ACTION" MySQL workbench automatically sets it to "RESTRICT"

I am trying to set a foreign key to constraint for on delete and on update to "NO ACTION", but for some reason after I apply the changes MySQL workbench changes it back to "RESTRICTED" on its own, I don't know why it's doing that.
This is the code MySQL Workbench generates when I try to change the constraints for on update and on delete to "NO ACTION"
ALTER TABLE `forums`.`post_replies`
DROP FOREIGN KEY `fk_post_replies_users`;
ALTER TABLE `forums`.`post_replies`
ADD CONSTRAINT `fk_post_replies_users`
FOREIGN KEY (`user_id`)
REFERENCES `forums`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
NO ACTION and RESTRICT are synonyms.
"13.1.20.5 FOREIGN KEY Constraints":
NO ACTION: A keyword from standard SQL. In MySQL, equivalent to RESTRICT.
Workbench seems to just pick to display RESTRICT over NO ACTION (well, it has to chose one and chooses the MySQL specific one...). But it doesn't mean anything different.

MySQL "Duplicate Foreign Key", but key doesn't exist

I need to create a foreign key, but executing the following results in the error: "Error Code: 1826. Duplicate foreign key constraint name 'FK_ProjectBase_Program'"
alter table ipos5.ProjectBase
add constraint FK_ProjectBase_Program foreign key (Program) references Program(OID);
If I execute:
select *
from information_schema.TABLE_CONSTRAINTS
where CONSTRAINT_TYPE = 'FOREIGN KEY'
result = def ipos5 FK_ProjectBase_Program ipos5 projectbase FOREIGN KEY
I can see the existing key definition, but if I show the structure for the target TABLE_NAME, it is not there.
This is on an active database with a large amount of data, using InnoDB, so dump/restore is a very last resort.
I am using a 3rd party framework, which does not allow me to manually specify a foreign key name (so I HAVE to use the one specified), but my application errors during startup because it cannot create the key.
Is there a way to rebuild the information_schema database? I am really hoping to avoid doing a dump and rebuild of the application database, as it is quite large.
I ended up duplicating the table structure, copying the data into it, dropping the original table, then re-creating it and copying the data back. Orphaned foreign key reference is now gone.

Foreign Key Constraint is incorrectly formed

There are several other questions about this topic that I have gone through, but I can't seem to figure out how their solutions apply to my tables. Check out the sqlfiddle. You can see it builds the schema just fine.
Basically, one table is a table of contacts/people. The second table is a table of countries. I am attempting to create a foreign key reference between contacts.country_id and countries.id.
Now, add the following to the panel on the left side:
ALTER TABLE `ultra_contacts`
ADD INDEX `fk_test` (`country_id`),
ADD CONSTRAINT `fk_test` FOREIGN KEY (`country_id`) REFERENCES `ultra_countries` (`id`) ON UPDATE CASCADE ON DELETE CASCADE`
The alter table code is not working for some reason. Any help would be appreciated.
The error is: Schema Creation Failed: Can't create table 'db_e342e.#sql-7711_1a4d2' (errno: 150): Using a 3rd party program (HeidiSQL) the error is a bit more detailed:
Foreign key constraint is incorrectly formed
You're trying to use foreign keys on a MyISAM table, which is not allowed (they only work with InnoDB). Take a look here: http://sqlfiddle.com/#!2/64951 All I've changed from your original is the table type (from MyISAM to InnoDB) and then I added the constraint. Worked fine.
Full disclosure - I'm the author of SQL Fiddle :)

Cascading delete removes unintended records

I typically develop in MS Access and occasionally connect to a MySQL back end. I have a MySQL back end that isn't cascading deletes as I'd expect when I delete records. I'm wondering if it's because of how I've set up the table relationships (foreign keys). I don't know enough about MySQL to know if I've done this right. In designer view I set up the relationships using the designer view in MySQL. For a composite primary key field (InterviewID, Coder ID) in tblInterviews I created two separate relations to tblSB for each of these two primary key fields (tblSB includes a 3rd field, SBid, as its composite PK). The designer view is a little different from Access in that you can't highlight more than one field at a time to set up relationships. I did find forums that discuss the syntax for setting up the relationship with the foreign key but I don't know if it's equivalent to what I did in designer. I suspect not because currently when I try to delete a specific record (unique InterviewID, CoderID combination) ALL interview records for the CoderID in the InterviewID, CoderID combination get deleted (and this cascades through to other child tables as well). I also am wondering if I need to set up my primary key in a way that I am not currently doing (e.g., setting it up as an index, also). Any help would be appreciated. Thanks in advance.
To see what you've created, look at the DDL. (SHOW CREATE TABLE)
To enforce foreign key constraints--including cascading deletes--you probably want to use the innodb engine. The myisam engine will accept DDL that declares foreign keys, but it won't enforce them.
MySQL will let a foreign key target a non-unique column. The MySQL docs say
Deviation from SQL standards: A FOREIGN KEY constraint that references
a non-UNIQUE key is not standard SQL. It is an InnoDB extension to
standard SQL.
They call it an extension to SQL. I call it a mistake.
It means you can declare tblSB.interviewID as a foreign key referencing tblInterviews.interviewID. A standard SQL dbms wouldn't allow that.
The 5.6 docs say
However, the system does not enforce a requirement that the referenced
columns be UNIQUE or be declared NOT NULL. The handling of foreign key
references to nonunique keys or keys that contain NULL values is not
well defined for operations such as UPDATE or DELETE CASCADE. You are
advised to use foreign keys that reference only UNIQUE and NOT NULL
keys.
To my way of thinking, they're saying, "It was a bad idea, but we don't know how to fix it. So it's up to you to avoid it. We could warn you when you try it, but we're not going to do that, either."
Based on your comments, I'd say this constraint is right . . .
CONSTRAINT tblInterviewRecordtblSB
FOREIGN KEY (InterviewID, CoderID)
REFERENCES tblinterviewrecord (InterviewID, CoderID)
ON DELETE CASCADE ON UPDATE CASCADE
but these two are not, and should be deleted.
CONSTRAINT tblSB_ibfk_1
FOREIGN KEY (InterviewID)
REFERENCES tblinterviewrecord (InterviewID)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT tblSB_ibfk_2
FOREIGN KEY (CoderID)
REFERENCES tblinterviewrecord (CoderID)
ON DELETE CASCADE ON UPDATE CASCADE

foreign key constraint

I'm having trouble editing the data in mysql with foreigh keys. When I try to update a foreign key, it says:
Cannot add or update a child row: a foreign key constraint fails (sadsystem/products, CONSTRAINT fk_ProductRelationship11 FOREIGN KEY (size_id) REFERENCES product_sizes (size_id))
The standard way of doing this is SET CONSTRAINTS DEFERRED.
However, MySQL/InnoDB does not support this. You will have to edit your data in consistency order: that is, you'll first have to create the target row in product_sizes before you can refer to its size_id from other tables.
(If you're sure you know what you're doing (such as when importing data), you can also temporarily disable the foreign_key_checks setting, but this does not check referential integrity when you re-enable it: any constraints broken while it was disabled will stay broken.)
When you update a column which is part (or all) of a foreign key, then the new value of the complete foreign key must reference a row in the referenced table. The error message is saying you are attempting to update the foreign key to a value that does not exist in the referenced table.