foreign key constraint - mysql

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.

Related

Is it not possible to have a check constraint reference a column that also has a foreign key?

I'm on MySQL 8 trying to add a check constraint:
ALTER TABLE `table` ADD CHECK (
(`column_a` IS NULL AND `column_b` IS NOT NULL) OR
(`column_a` IS NOT NULL AND `column_b` IS NULL)
);
but I keep getting this error:
Column 'column_b' cannot be used in a check constraint 'table_chk_1': needed in a foreign key constraint 'table_ibfk_2' referential action.
I can't find any reference to this error anywhere else on the internet and I don't understand what the problem is.
Both column_a and column_b are also foreign keys to other tables and they are both nullable. I just want to make sure that each row in table has either a reference via column_a or via column_b.
What is the cause of this error?
What have I tried
I've tried to drop the foreign keys, add the check constraints and it succeeds. Then if I add the foreign key back to column_b I still get the same error.
This is a documented behavior:
Foreign key referential actions (ON UPDATE, ON DELETE) are prohibited on columns used in CHECK constraints. Likewise, CHECK constraints are prohibited on columns used in foreign key referential actions.
So you need to choose between having a referential action on your column, or having a check constraint. Alternatively, you can keep the referential action and implement the check logic using triggers (or keep the check constraint and implement the referential action in a trigger!).

Getting "#1452 - Cannot add or update a child row." In phpmyadmin

Here is the complete database
(removed link to google drive download, go to revisions if you have to see it. A simple .gif would suffice.)
So I'm trying to use the universityName primary key from the university table as a foreign key In the resource table. And every time I try to set it up using the relation view in phpmyadmin I keep getting the error "Getting "#1452 - Cannot add or update a child row: a foreign key constraint fails (bluemtn.#sql-28f8_332, CONSTRAINT #sql-28f8_332_ibfk_1 FOREIGN KEY (universityName) REFERENCES university (universityName))
I had some spaces before and after a few of names in the universityName column that was preventing me from adding the foreign key constraint because mysql thought I had values that where not in my referenced table.

Mysql Foreign Key Creation

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.

MySQL error 1452

Here's the script
ALTER TABLE `candycorn`.`bb_users`
ADD CONSTRAINT `pf_minecraftusername`
FOREIGN KEY (`pf_minecraftusername`)
REFERENCES `candycorn`.`bb_profile_fields_data` (`pf_minecraftusername`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
and the error description
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(`candycorn`.<result 2 when explaining filename '#sql-4e4_1785d'>, CONSTRAINT
`pf_minecraftusername` FOREIGN KEY (`pf_minecraftusername`) REFERENCES
`bb_profile_fields_data` (`pf_minecraftusern)
if somebody could, would you explain what I'm missing out here?
The constraint that you are trying to add isn't satisfied by some data already in the tables. This can be because a value in bb_users table isn't found in the corresponding column (pf_minecraftusername) in bb_profile_fields_data.
If you have to add the constraint to tables with data already in them, you have to clean up the tables by hand first. Alternatively, you can empty the tables (with truncate, or by making the tables afresh after doing a "drop database"), then add the constraint, and then run whatever scripts you have to put data in the tables.
Of course, if this is a production system, you'll need to do more complex data fixing before you can successfully add the constraint.
Finally, I suggest that you make a dummy copy of the database with no data at all and add the constraint there, just to check that the constraint is properly specified. You don't want to be barking up the wrong tree.
ALTER TABLE tablename with NOCHECK
ADD CONSTRAINT [FK_1] FOREIGN KEY ([Column name])
REFERENCES restaurants([column name])
It seems data is already present in table.. So
You need to modify table using above query.. No need to recreate table nd data

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