Mysql foreign key - php

so i am trying again and again to make a column as a foreign key but it gives me Constraint name error? what Constraint name should i put? i am using PHPmyadmin SQL , I tried giving it names such as trackid and so on but still i am getting an error
ALTER TABLE `ss_ordered_carts`
ADD CONSTRAINT `track_id` FOREIGN KEY (`track_id`)
REFERENCES `ProjectDatabase`.`ss_orders` (`track_id`)
ON DELETE RESTRICT ON UPDATE CASCADE;
MySQL said: Documentation
1452 - Cannot add or update a child row: a foreign key constraint fails (projectdatabase.
'#sql-1414_6c7'>, CONSTRAINT track_id FOREIGN KEY (track_id) REF
ERENCES ss_orders (track_id) ON UPDATE CASCADE)

If you have data in child table for the referred column field, to add foreign key on that field,
first you have to disable foreign key checking.
And then alter to add foreign key.
And lastly reset the constraint checking.
Step 1: Disable the foreign key checks.
set foreign_key_checks=0;
Step 2: Now add the foreign key constraint.
ALTER TABLE `ss_ordered_carts`
ADD CONSTRAINT `track_id` FOREIGN KEY (`track_id`)
REFERENCES `ProjectDatabase`.`ss_orders` (`track_id`)
ON DELETE RESTRICT ON UPDATE CASCADE;
Step 3: Now reset the foreign key checks.
set foreign_key_checks=1;

It is possible that you have table ss_ordered_carts filled with wrong data, that cannot be related. Check it using this query -
SELECT * FROM ss_ordered_carts t1
LEFT JOIN ss_orders t2
ON t1.track_id = t2.track_id
WHERE
t2.track_id IS NULL;
Then modify table's data, and after, create foreign key.

Try this.
mysql> SET foreign_key_checks = 0;
mysql> ALTER TABLE ss_ordered_carts
ADD CONSTRAINT track_id
FOREIGN KEY(track_id)
REFERENCES ss_orders(track_id)
mysql> SET foreign_key_checks = 1;
May be, you are getting the specified error as there exists data in the tables.
This may also occur if child table contain some data with the foreign key that that are not in parent table. In this case try,
Delete from child where child_id NOT IN (select parent_id from parent where parent.id = child.id)

Related

MySQL cascade delete on self-referencing parent-child table?

I have this MySql database table:
tbl_project
id
project_name
parent_id
If a project is a 'parent', parent_id is 0.
Now I'm trying to add a self referencing foreign key
CONSTRAINT `FK_tbl_project_tbl_project` FOREIGN KEY (`parent_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE
When I try to insert a new record,
SQL Error (1452): Cannot add or update a child row: a foreign key constraint fails (mydbname.#sql-3539_d7d, CONSTRAINT FK_tbl_project_tbl_project FOREIGN KEY (parent_id) REFERENCES tbl_project (id) ON DELETE CASCADE)
Basically I just want all the children to be deleted when I delete the parent. What am I missing here?
When you enter any value into the parent_id column of a new row, the foreign key requires that there is a row where id has that value, because that's how foreign keys work.
If you want to use a foreign key with your self-referencing relationship, you should use NULL instead of 0 for the parent_id of a row that has no parent to reference. Foreign keys ignore NULL.

MySQL Error Code 1215: Cannot add foreign key Constraint on ALTER TABLE : Mysql

I want to add foreign key Constraint on my existing tables(type InnoDB)
,I have two tables listed below:
tbl_users : [ user_id(INT,AUTO_INCREMENT), user_name,--- etc]
tbl_users_meta : [ user_meta_id(INT,AUTO_INCREMENT), user_id(INT),--- etc]
I have already created index 'user_id' on 'tbl_users_meta' listed below :
Here is my Query but i am getting (MySQL Error Code 1215: ) each time.what is the problem i can getting it ?
ALTER TABLE `tbl_users_meta`
ADD CONSTRAINT `fk users user_id`
FOREIGN KEY (`user_id`) REFERENCES
`sanskrut`.`tbl_users`(`user_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
TRY with the same query you have writen with a small modification:
ALTER IGNORE TABLE `tbl_users_meta`
ADD CONSTRAINT `fk users user_id`
FOREIGN KEY (`user_id`) REFERENCES
`sanskrut`.`tbl_users`(`user_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
Hope it'll work
I can't see anything wrong with what you've written, so there must be something you haven't posted affecting the problem. For example, on MySQL version 5.5.44, I can successfully execute the following:
CREATE DATABASE sanskrut;
USE sanskrut;
CREATE TABLE tbl_users (user_id INT AUTO_INCREMENT PRIMARY KEY, user_name VARCHAR(50));
CREATE TABLE tbl_users_meta (user_meta_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT);
CREATE INDEX user_id ON tbl_users_meta (user_id);
ALTER TABLE `tbl_users_meta`
ADD CONSTRAINT `fk users user_id`
FOREIGN KEY (`user_id`) REFERENCES
`sanskrut`.`tbl_users`(`user_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
...which finishes with your exact problem statement, copied and pasted, and works just fine.
I'd suspect, as I mentioned in the comments, that there's an index missing or possibly a datatype mismatch. You may find it helpful to add the output of:
DESC tbl_users;
DESC tbl_users_meta;
SHOW indexes FROM tbl_users;
SHOW indexes FROM tbl_users_meta;
...to your question.

How to add "ON UPDATE SET NULL" to foreign key constraint?

How can I use the Laravel Schema Builder to add "ON UPDATE SET NULL" to my foreign key constraint?
I do not understand why to set as null on update; but this is the idea:
You can delete the existent constraint.
ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;
And create it again
ALTER TABLE tbl_name
ADD CONSTRAINT my_new_FK
FOREIGN KEY (column_in_this_table)
REFERENCES other_table (other_table_pk_column)
ON DELETE SET NULL;
You can find more information about constraints and the alter table statement in the mysql documentation.
Using FOREIGN KEY Constraints
ALTER TABLE Syntax

Relate DB id's Mysql

I would like to know how can I relate 2 id's. One frome users table and another from stats table. The id from users is AI , Primary and I want to relate the other id to this one.
I tried Foreign key constraint (INNODB) and it gave me this error #1452 - Cannot add or update a child row: a foreign key constraint fails (game.#sql-3de_34f, CONSTRAINT ?sql?3de_34f_ibfk_1 FOREIGN KEY (id) REFERENCES user (id)) .
Thanks
Try this!
SET foreign_key_checks = 0;
Then run query to add your key, and after that...
SET foreign_key_checks = 1;
You have USER_IDs in your "stats" table that are not in your "users" table.
Delete them if you think they are not useful anymore.
DELETE FROM stats where user_id NOT IN (SELECT user_id from users);
Then, you can create your reference keys.

On delete cascade - where I have to add it

I needed an example of cascade delete. My question is, where do I add it? In the table I create PK, or in other tables where this PK is sitting there as FK?
Can I use "alter table" to add "on delete cascade" to existing table? An example please?
#edit
MYSQL, using phpMyAdmin
#edit 2
Does it look good?
alter table wplaty
drop foreign key pesel,
add constraint pesel foreign key (pesel)
references baza_osob(pesel) on delete cascade on update restrict;
My parent table = baza_osob
My child table = wplaty
PK is pesel, FK is pesel as well.
#edit3
Got error:
#1025 - Error on rename of '.\projekt\wplaty' to '.\projekt#sql2-1300-6c' (errno: 152)
cascade directives go into the "child" tables, e.g.
create table parent (
id int primary key
)
create table child (
id int primary key
parent_id int,
foreign key (parent_id) references parent (id)
on delete cascade
)
Never tried doing an alter on a foreign key to change its on settings, but worst case, you simply drop the existing FK and redefine it with the new on settings in place.
You actually don't add the 'ON DELETE CASCADE' on a table. It's part (or not) of each Foreign Key definition.
You need to enable this option for the foreign key. If you did not add this option when you created foreign key, then you should recreate it.
alter table <table> drop foreign key <fk name>;
alter table <table> add constraint <fk name> foreign key (<column name>)
references <ref tble>(<ref column) on delete cascade on update restrict;
In one statement:
alter table <table>
drop foreign key <old fk name>,
add constraint <new fk name> foreign key (<column name>)
references <ref tble>(<ref column) on delete cascade on update restrict;

Categories