Relate DB id's Mysql - php

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.

Related

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.

Cannot add or update a child row: a foreign key constraint fails. what is this?

sorry, i am still new in php... i want to ask... how actually foreign key is functional? i mean, i have create a foreign key and primary key, everything fine. i try look in internet, but still i cant make it work or did mistake that i dont know. i get this error "Cannot add or update a child row: a foreign key constraint fails" when i try to insert information inside my other table that have foreign key
my parent table "user_information" have:
user_id = primary key
user_password
name
user_category
group_id
and my other "table vehicle_registration" have:
plate_number = primary key
user_id = foreign key
roadtax_validation
vehicle_category
user_option
insurance name
i want to make the user that log in can insert their vehicle registration, and it bind to that user, the user_id should be similar, just other information is diferent... how i can make it? is it correct that the foreign key is to work like that? cause when i try to insert value inside the vehicle_registration it will show "Cannot add or update a child row: a foreign key constraint fails"
can someone explain how it actually done?
You have to add user/s first. You can't add a record in vehicle_registration table if you dont have a matching record in the parent table.
That is how foreign key constraint works. For example if you have a record in user_information table with user_id = 1, you are only allowed to have records with user_id = 1 in the vehicle_registration table. And so on...

Mysql foreign key

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)

A foreign key constraint fails

I am relatively new in php and mysql.The problem that i am facing while i inserting value in my leave table.My leave table containing following column..
1.lid(INT primary key)
2.empname(varchar)
3.username(varchar)
4.nod(INT)
5.sdate(DATE)
6.edate(DATE)
7.reason(varchar)
8.action(varchar)
9.empID (INT FOREIGN KEY)
here empID is the foreign key references from users table. The problem that im facing while inserting values into the leave table.ERROR is given below
Cannot add or update a child row: a foreign key constraint fails (db_attendance1.leave, CONSTRAINT leave_ibfk_1 FOREIGN KEY (empID) REFERENCES users (empID))
here i just send the query and here it is..
mysql_query("INSERT INTO `leave`
(`empname`, `username`,
`nod`, `sdate`, `edate`,
`reason`,`action`)
VALUES ('$empname', '$username',
'$nod', '$sdate',
'$edate', '$reason','');",
$dbCon) or die(mysql_error());
You can put
SET FOREIGN_KEY_CHECKS=0;
and run your query. Once you are done again set it back to 1 by
SET FOREIGN_KEY_CHECKS=1;
A foreign key constraint means that you one table doesn't accept inserts, updates or deletes that would 'break' the foreign key. This means, you can't update a EmpID if the new EmpID doesn't exist in the users. You can't add a new EmpID if it doesn't exist in the users table, etcetera.
So to solve this issue, you need to make sure that the EmpID you're trying to add to table 'leave', first exists in table 'users'.
Foreign keys can be a real powerful item, but can be a real pain too. Since the DB you're working on had foreign key constraints, I suggest you read on them a bit: http://en.wikipedia.org/wiki/Foreign_key
Borniet, you helped me solve my similar problem.
#OP - All I had to do to fix this was create a corresponding row in the table so that the foreign key would exist.
E.g. Table 1 has column Name
Table 2 has column friends_name, a foreign key tied to Name in table 1.
I got this error because I was trying to insert a row into table 2, where the friends_name referenced a non existing Name in table 1. So I created the name and we're off to the races :).

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

So the scenario is this:
I create a group with a form, stored in test_groups_tb, then with another form enter user ids to attach them to the group and they are stored in group_association_tb with a structure like so:
group_id | user_id
I am very new to MySQL and more so Foreign Key relationships, so I tried to set up a relationship on group_association_tb which was basically, if the group was deleted, delete all records of that group from group_association_tb.
now what Is happening since applying this is the group is stored fine. I can add students manually fine, but when I try adding them by importing a csv it doesn't like it.
here is the queries (i know its not efficient querying every iteration):
while($row = mysql_fetch_assoc($result))
{
$sql = "INSERT INTO group_association_tb (group_id, user_id)VALUES('$group','".$row[user_id]."')";
mysql_query($sql) or die(header("Location:error.php"));
}
here is the error i get:
Cannot add or update a child row: a foreign key constraint fails (`ece70141/group_association_tb`, CONSTRAINT `group_association_tb_ibfk_1` FOREIGN KEY (`group_id`) REFERENCES `test_groups_tb` (`group_id`) ON DELETE CASCADE)
could somebody explain what the problem is here.
many thanks,
For those encountering the problem " ERROR 1216: Cannot add or update a child row: a foreign key constraint fails", it actually means what it says! Some row in the child does not comply with the constraint, correct the problem.
You find the rows like this:
select child.id from child left join parent on (child.parent_id=parent.id) where child.id is not null and parent.id is null;
(from http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html)
EDIT: I think that you need to invert the constraint. test_groups_tb needs to reference the grop_association_tbl.
It looks like you have not added the group_id that you are referencing from the group_association_tb table to the test_group_tb table. If a foreign key from group_association_tb references a key in test_group_tb, the key has to be in test_group_tb before you can add it to group_association_tb.
For instance:
I have a table (user_group)_ defined as follows:
group_id, first_name, last_name
And another (group_permission) as follows:
group_id, permission_name
if I create a foreign key from group_permission that references user_group, I cannot add a row to group_permission with a group_id that doesn't exist in user_group already. First, I have to create the row in user_group with a given group_id, then insert into the group_permission table with the group_id of the associated row in user_group.

Categories