Weird mysql behavior when adding foreign key - sql

I am trying to add a simple foreign key like so
ALTER TABLE `4over4local`.`wf_job_status`
ADD CONSTRAINT `fk_sales_job_status_sales_job1`
FOREIGN KEY (`job_id`)
REFERENCES `4over4local`.`sales_job` (`job_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
But i am getting a very weird error with some database table named #sql-d74_9 that doesn't even exist.
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`4over4local`.`#sql-d74_9`,
CONSTRAINT `fk_sales_job_status_sales_job1` FOREIGN KEY (`job_id`) REFERENCES `sales_job` (`job_id`)
ON DELETE CASCADE ON UPDATE CASCADE)
I have previously made very similar queries and they all worked fine except this one. What could cause this and what i am doing wrong? I am using MariaDB 13

The error indicates that you have rows in the table that do not satisfy the foreign key constraint you are trying to add. You need to fix your data before you can create the constraint.
You can exhibit offending rows with the following query:
select wjs.*
from wf_job_status wjs
where not exists (select 1 from sales_job sj where sj.job_id = wjs.job_id)

Related

How to put Cascade on Delete once the Fk constraint has already been defined [duplicate]

I have a table representing users. When a user is deleted I get:
DELETE statement conflicted with the REFERENCE constraint
Apparently, CASCADE DELETE is not as easy as I imagined in SQL Server, and the option needs to be added to the table.
The problem is: I cannot figure out how to add the CASCADE DELETE option.
I'm using: SQL Server 2008. Any ideas how to do this?
Read this Microsoft article first. Read Me. I use the GUI during design so here is a picture of how it is selected in SSMS.
The syntax added to the foreign key is " ON DELETE CASCADE "
Here's the way I would add the "cascading delete" feature to an existing foreign key in SQL Server Management Studio.
First, find your foreign key, and open it's "DROP and CREATE To" in a new Query window.
Then, just add "ON DELETE CASCADE" to the "ADD CONSTRAINT" command:
Then just hit hit the "Execute" button to run the query.
Job done !
Google ALTER TABLE DROP CONSTRAINT, then ALTER TABLE ADD CONSTRAINT:
ALTER TABLE
Here's a quick example:
CREATE TABLE A
(
ID INTEGER NOT NULL UNIQUE
);
CREATE TABLE B
(
ID INTEGER NOT NULL UNIQUE
CONSTRAINT fk__B__A
REFERENCES A (ID)
);
-- Oops! Forgot the CASCADE referential actions.
-- DROP the constraint then recreate it:
ALTER TABLE B DROP
CONSTRAINT fk__B__A;
ALTER TABLE B ADD
CONSTRAINT fk__B__A
FOREIGN KEY (ID)
REFERENCES A (ID)
ON DELETE CASCADE
ON UPDATE CASCADE;

Firebird: Alter "anonymous" foreign key

I need to alter an existing foreign key from "on delete restrict" to "on delete cascade". Unfortunaltey this bug sneaked through Q/A.
In my database I have several forign key relationships that were automatically named (INTEG_1, INTEG_2, ...). The name of the constraint I have to fix is another in a new installation than in an Update from Version 2 and even another than when this Version 2 previously has been updated from Version 1.
As the referencing table only has one foreign key, this statement gives me the name of the constraint:
SELECT RDB$CONSTRAINT_NAME
FROM RDB$RELATION_CONSTRAINTS
where RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'
and RDB$RELATION_NAME = 'MY_TABLE_NAME'
then I can drop and afterwards recreate the foreign key (with a "real" name this time)
alter table MY_TABLE_NAME
drop constraint <result from above>;
alter table MY_TABLE_NAME
add constraint fk_my_table_name_purpose foreign key (other_id)
references other_table(id) on delete cascade;
However, I try to avoid working directly with system tables and I'd like to know whether there is a better / more elegant way to alter my foreign key.
There's no better way, the system tables are the only way to figure out the constraint name.

Unable to add foreign key constraint due to obscure conflict

Trying to run :
ALTER TABLE [dbo].[Table1] ADD
CONSTRAINT [FK_Table1_ScenarioResult]
FOREIGN KEY ([ScenarioResultID]) REFERENCES [dbo].[ScenarioResult] ([ScenarioResultID]) ON DELETE CASCADE
Getting this error :
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Table1_ScenarioResult". The conflict occurred in database "8362", table "dbo.ScenarioResult", column 'ScenarioResultID'.
I have checked :
Constraint does not already exist, and no other exists on same column
The values in the column match in both tables
Types of columns are the same
Tried a different name, also fails
On SQL Server 2008 R2
Any ideas what I could try?
In theory this might work:
ALTER TABLE [dbo].[Table1] WITH NOCHECK ADD
CONSTRAINT [FK_Table1_ScenarioResult]
FOREIGN KEY ([ScenarioResultID]) REFERENCES [dbo].[ScenarioResult] ([ScenarioResultID])
ON DELETE CASCADE
Not sure how you checked for integrity of existing values, but it should be:
SELECT COUNT(*) as Orphans FROM [dbo].[Table1] t
WHERE NOT EXISTS
(SELECT * FROM [dbo].[ScenarioResult] WHERE ScenarioResultID = t.ScenarioResultID)
If "Orphans" is greater then zero you need to clean the data before adding a constraint.
This one was baffling me aswell, and then the penny dropped.
I was trying to create a Foreign Key using "Database Diagrams" in SQL Server 2012, but it refused to let me as it claimed to clash with the foreign key I was trying to create. Huh ?
But, I had accepted the defaults to "Enforce foreign key constraint". But I already had data in the two tables I was attempting to create a foreign key for, and it was breaking the foreign key rule I was trying to make, so SQL Server was rejecting the new key.
The solution (in this particular case) was to change "Enforce foreign key constraint" to "No", or at least until I had cleaned up my data.
Hope this helps.
I had the same issue
I clear the data of the tables where i want to edit the content and add a new foreign key constraint and retry.
It works for me.
I hope it help you.

SQL query error - can't see why?

I'm currently reading through this Yii application eBook: http://www.packtpub.com/agile-web-application-development-yii11-and-php5/book - and I'm having a problem inputting the tutorials DDL / SQL statements into PHPMyAdmin without it throwing up errors.
Would someone be kind enough to shed some light on why the following syntax is invalid? It might be something simple but I can't see it:
SQL statement:
ALTER TABLE tbl_issue
ADD CONSTRAINT FK_issue_project FOREIGN KEY (`project_id`)
REFERENCES tbl_project(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE tbl_issue
ADD CONSTRAINT `FK_issue_owner` FOREIGN KEY (`owner_id`)
REFERENCES tbl_user(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE tbl_issue
ADD CONSTRAINT `FK_issue_requester` FOREIGN KEY (`requester_id`)
REFERENCES tbl_user(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE tbl_project_user_assignment
ADD CONSTRAINT `FK_project_user` FOREIGN KEY (`project_id`)
REFERENCES tbl_project(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
ALTER TABLE tbl_project_user_assignment
ADD CONSTRAINT `FK_user_project` FOREIGN KEY (`user_id`)
REFERENCES tbl_user(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
INSERT INTO tbl_user (`email`, `username`, `password`)
VALUES
(`test1#notanaddress.com`,`Test_User_One`, MD5(`test1`)),
(`test2#notanaddress.com`,`Test_User_Two`, MD5(`test2`));
Error Message
Error
SQL query:
ALTER TABLE tbl_issue
ADD CONSTRAINT FK_issue_project FOREIGN KEY ( `project_id` )
REFERENCES tbl_project( `id` ) ON DELETE CASCADE ON UPDATE RESTRICT ;
MySQL said:
#1005 - Can't create table 'trackstar_test.#sql-c78_127' (errno: 121) (<a
href="server_engines.php?engine=InnoDB&page=Status&
token=252c0553975923580ca430b6e98c4243">Details...</a>)
Note:
All the tables in the database are set to innodb as their storage engine.
I've tried using different foreign key names for each FK, still get the same error.
Update:
After finding no solution to the problem, I deleted by DB, uninstalled Xampp and then redid everything again. Seems to work now. Sorry to not be able to tell future readers exactly what the cause was, but it was most probably to do with my Database config or the information I added to it.
Actual Problem is :
AS you are Following the book, there are a few insert/ update statements are executed on
tbl_proect,
tbl_issue
than you are trying to add Foreign Key Constraint. that checks the table data before applying. So, Here is the actual mistake, may be your tables contain a few records that violate the foreign key constraints. hence phpmyadmin doesnot allow you to alter table and generates error message.
Solution :
TRUNCATE TABLE `tbl_project`
TRUNCATE TABLE `tbl_issue`
Do Only one thing, clear all the tables . Empty tables. . And here's your problm resolved now phpmyadmin allows you to run commands.

Creating a foreign key in MySQL produces error:

I'm trying to create a foreign key on a table in MySQL and I'm getting a strange error that there seems to be little info about in any of my searches.
I'm creating the key with this (emitted from mysql workbench 5.2):
ALTER TABLE `db`.`appointment`
ADD CONSTRAINT `FK_appointment_CancellationID`
FOREIGN KEY (`CancellationID` ) REFERENCES `db`.`appointment_cancellation` (`ID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `FK_appointment_CancellationID` (`CancellationID` ASC) ;
at which point I get the error:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (alarmtekcore., CONSTRAINT FK_lead_appointment_CancellationID FOREIGN KEY (CancellationID) REFERENCES lead_appointment_cancellation (`)
I've checked here
but there's no data in the table.
You can't apply a foreign key constraint on a column with pre-existing data that doesn't already exist in the parent table.
If you run the following to populate the appointment_cancellation table, you should be able to apply the foreign key afterwards:
INSERT INTO appointment_cancellation
SELECT DISTINCT a.CancellationID
FROM appointment
The two fields - appointment.CancellationID and appointment_cancellation.ID - need to be exactly the same type. If one is INT and the other is INT UNSIGNED, you'll get this error.