How do I avoid foreign key constraint fail error - - mysql

I am currently using dreamweaver and I am trying to insert a record insertion wizard connected to a mysql server. However when I try to update the column I get a foreign key constraint fail and I can understand this is due to me creating a non existent foreign key.But how else can I use an input wizard.
database
Here is the data model.
The column I am trying to update is "kommentar" but it is not working, any ideas?

Tough to say with the info provided, but in all likelihood the value you're using in hotellid doesn't have a corresponding entry in the table hotell.

You could run the same wizard for the hotels and add a hotel with your desired hotelid, before inserting into kommentar

Related

Upsert Only inserts and does not update the existing field

I am trying to add attendances to the attendance table and if attendance of the give date and student id is already in the table I need to update the attendance type.
But the upsert is only inserting and it does not ever update.
SmStudentAttendance::upsert($studentRows, ['student_id', 'attendance_date'], ['attendance_type']);
It's too late but it worked for me. Try this in a migration:
$table->unique(['student_id', 'attendance_date']);
Or you can add unique constraints to the columns in phpmyadmin (or a similar tool)
upsert works exactly like
on duplicate key update on MySQL
which needs a unique constraint violation to update instead of an insert.
So check if you have such a violation, directly in the database.
Also you can read more about with an example for example at https://www.amitmerchant.com/insert-or-update-multiple-records-using-upsert-in-laravel8/

How do I get MySQL tables to update each other?

I'm new to programming so please forgive my ignorance. I'm trying to get MySQL tables to update each other. For example: When I insert data into a Primary Key column in one table, it does not appear in it's Foreign Key column in another table.
Does anyone have any advice on this issue?
Thank you!
Additional Information: I used phpMyAdmin to create my tables and then added SQL code to create the Foreign Keys. Example of code is below.
ALTER TABLE CourseSchedule
ADD FOREIGN KEY (CourseId)
REFERENCES Course(CourseId)
I believe what we have here is a slight misunderstanding of the documentation.
For storage engines supporting foreign keys, MySQL rejects any INSERT
or UPDATE operation that attempts to create a foreign key value in a
child table if there is no a matching candidate key value in the
parent table.
When an UPDATE or DELETE operation affects a key value in the parent
table that has matching rows in the child table, the result depends on
the referential action specified using ON UPDATE and ON DELETE
subclauses of the FOREIGN KEY clause. MySQL supports five options
regarding the action to be taken, listed here
What your foreign key actually does is to make sure that you cannot insert values into your CourseSchedule table that do not correspond to an entry in the Courses table.
To give you an example, suppose you were to try to enter schedule a python course for every wednesday at 9:00 but you dont' actually have an entry for python in your Courses table. Then mysql will refuse to create that entry. Mysql cannot do the reverse. It doesn't know details about your python course. So it cannot automatically create a entry in the Courses table for you. Similarly, if oyu created an entr in the courses table. Mysql cannot automatically create a CourseSchedule for you because it doesn't know at what time it should be scheduled.

MySQL "Cannot add or update a child row: a foreign key constraint fails"

I'm new to MySQL and databases in general. I've been tasked with manually moving an old database to a new one of a slightly different format. The challenges include transferring certain columns from a table in one database to another database of a similar format. This is made further difficult in that the source database is MyISAM and the destination is InnoDB.
So I have two databases, A is the source and B is the destination, and am attempting to copy 'most' of a table to a similar table in the destination database.
Here is the command I run:
INSERT INTO B.article (id, ticket_id, article_type_id,
article_sender_type_id, a_from, a_reply_to, a_to, a_cc, a_subject,
a_message_id, a_in_reply_to, a_references, a_content_type, a_body,
incoming_time, content_path, valid_id, create_time, create_by,change_time,
change_by)
SELECT id, ticket_id, article_type_id, article_sender_type_id,
a_from, a_reply_to, a_to, a_cc, a_subject, a_message_id, a_in_reply_to,
a_references, a_content_type, a_body, incoming_time, content_path,
valid_id, create_time, create_by, change_time, change_by
FROM A.article
WHERE id NOT IN ( 1 );
Error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`helpdesk`.`article`, CONSTRAINT `FK_article_ticket_id_id` FOREIGN KEY (`ticket_id`) REFERENCES `ticket` (`id`))
The reason for making the command so wordy is that the source has several columns that were unnecessary and so were pruned out of the destination table. The WHERE id NOT IN ( 1 ) is there so that the first row is not copied (it was initialized in both databases and MySQL throws an error if they both have the same 'id' field). I can't tell by the error if it expects 'ticket_id' to be unique between rows, which it is not, or if it is claiming that a row does not have a ticket_id and so can not be copied which is what the error seems to most often be generated by.
I can post the tables in question if that will help answer, but I am unsure of the best way to do that, so some pointing in the right direction there would be helpful as well.
Posts I looked at before:
For forming the command
For looking at this error
Thanks!
You'll want to run a SHOW CREATE TABLE on your destination table:
SHOW CREATE TABLE `B`.`article`;
This will likely show you that there is a foreign key on the table, which requires that a value exist in another table before it can be added to this one. Specifically, from your error, it appears the field ticket_id references the id field in the ticket table. This introduces some complexity in terms of what needs to be migrated first -- the referenced table (ticket) must be populated before the referencing table (article).
Without knowing more about your tables, my guess is that you haven't migrated in the ticket table yet, and it is empty. You'll need to do that before you can fill in the B.article table. It is also possible that your data is corrupt and you need to find which ticket ID is present in the article data you're trying to send over, but not present in the ticket table.
Another alternative is to turn off foreign key checks, but if possible I would avoid that, since the purpose of foreign keys is to ensure data integrity.

how to repair data so foreign keys can be added back to database

I have just discovered my database which has been moved between a few servers in the last few months was, in one of the database dumps, converted to myisam and all the foreign key constraints nuked (not impressed). I've converted all the tables back to innodb with a php script but now I'm finding half the constraints are failing to add.
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`identicar2`.<result 2 when explaining filename '#sql-2a7_c0'>, CONSTRAINT `#sql-2a7_c0_ibfk_1` FOREIGN KEY (`feature_sk`) REFERENCES `tbl_feature_list` (`feature_sk`))
I'm lost now, I can't go through thousands of records manually. what is the best thing to do in order to get my database back into shape?
I can provide table structures if you want but I imagine any solution will be independant of the exact structure anyway
The simplest solution: (containing the obvious danger of losing data you may want to keep)
UPDATE table
SET fkColumn = NULL
WHERE fkColumn NOT IN (SELECT referenceColumn FROM referencedTable)
If you just want to find them:
SELECT *
FROM table
WHERE fkColumn NOT IN (SELECT referenceColumn FROM referencedTable)

foreign key constraint giving issue while inserting records

I m trying to import data from one table to another table across the schema.but foreign key constraint is giving issue.
Suppose i m having schema one and schema two.
schema one has tables -->
user
behavior
userbehavior(id from user and behavior table are foreign keys in
userbehavior table)
same way i have tables structure in schema two.
schema 2 has tables-->
user1
behavior1
userbehavior1(id from user and behavior table are foreign keys in userbehavior table)
I have successfully imported records from user to user1 and behavior to behavior1 but when I m trying to import data from userbehavior to userbehavior1 i m getting following error::
cannot add or update a child row.foreign key constraint fails.
wat could be an issue?
Thanks in advance.
You have inconsistent data, which the database refuses to import, and for a good reason.
I'd create TEMPORARY tables (i.e. tables that are automatically deleted after the session ends, import the data there, use a few queries that show me the rows from userbehaviour that violate the FOREIGN KEY constraint, clear these up manually and then use SELECT INTO to copy the data to the real tables.
cause : There is at least one row in table userbehaviour which have no parent in other table
todo: first remove all foreign key constraints from both schema and Insert and then set constraint back
In case of exporting
open exported sql file and write
SET FOREIGN_KEY_CHECKS=0; on the top of the file
and SET FOREIGN_KEY_CHECKS==1; on the bottom of file
or
export through phpMyAdmin then check Disable foreign key checks