Creating foreign key between 2 tables - mysql

Ok, so it's like this. I have 2 tables in phpmyadmin. One is for personal details and the other is for login information. Both tables have AccountID, so I tried using foreign key constraints to connect the tables. After I did that it seems like I cannot update the table with new data. Before the constraint, updating the tables worked fine.
What I'm trying to do is store user login info and personal info in these table. Then whenever the user wants to delete their current account, the personal details and login details of are deleted from both tables or when they wanted to search for their login and personal info the search engine can search from both tables with AccountID.
so far.i have make 2 new tables.1 table which is personal information have 'AccountID'[A_I][PRIMARY] and 'loginID'.another table is login info.it has 'loginID'[A_i][PRIMARY]
i already make the 'loginID' at personal info and index but i cannot assign foreign key constraint for it bcause it did not detect 'loginID' in personal info.

Your AccountId should be a primary key in one table say Personal Info table.
This AccountId should be the foreign key in another table (Login) and make sure you set on Delete Cascade and on Update Cascade.
So in this structure, when personal info is deleted, its corresponding record in the login table will be automatically deleted.
DROP TABLE IF EXISTS `stacktest`.`personal_info`;
CREATE TABLE `stacktest`.`personal_info` (
`account_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`age` varchar(45) DEFAULT NULL,
PRIMARY KEY (`account_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `stacktest`.`login_info`;
CREATE TABLE `stacktest`.`login_info` (
`loginId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`account_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`loginId`),
KEY `FK_login_info_1` (`account_id`),
CONSTRAINT `FK_login_info_1` FOREIGN KEY (`account_id`) REFERENCES `personal_info` (`account_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
Above is the way how the 2 tables should be created.
Then insert some values in both table,
Note that account_id value has to be same in both the tables.
After that you can fire a delete query like:
delete from personal_info where accound_id=2;
This will delete rows from parent table personal_info and also from child table login_info where account_id is 2
Keeping the account_id as NOT NULL in child table:
DROP TABLE IF EXISTS `stacktest`.`login_info`;
CREATE TABLE `stacktest`.`login_info` (
`loginId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`account_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`loginId`),
KEY `FK_login_info_1` (`account_id`),
CONSTRAINT `FK_login_info_1` FOREIGN KEY (`account_id`) REFERENCES `personal_info` (`account_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

Related

MySQL alter two column for same foreign key

I have a table called user and the primary key is user_id.
I have another table called follows. This table is for storing which user follow which user(it is something like twitter follow function).
This is my follow table.
CREATE TABLE `follows` (
`id` int(11) NOT NULL,
`orginal_user_id` int(11) NOT NULL,
`follow_user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `follows`
ADD PRIMARY KEY (`id`);
So, how can I alter this table to set both orginal_user_id and follow_user_id as a foreign key of user_id of user table...
If a user is deleted from the user table, I want to automatically delete rows in follows table either that user id appears on an orginal_user_id column or follow_user_id column.
You may use cascading delete constraints in your table:
CREATE TABLE follows (
id int(11) NOT NULL PRIMARY KEY,
orginal_user_id int(11) NOT NULL,
follow_user_id int(11) NOT NULL,
CONSTRAINT fk_original_user FOREIGN KEY (orginal_user_id)
REFERENCES user(id) ON DELETE CASCADE,
CONSTRAINT fk_follow_user FOREIGN KEY (follow_user_id)
REFERENCES user(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

how to use foreign key for auto-incremented records?

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`student_id` int(11) NOT NULL AUTO_INCREMENT,
`student_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=901840505 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `grades`;
CREATE TABLE `grades` (
`grade_id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) DEFAULT NULL,
`grade` varchar(45) DEFAULT NULL,
PRIMARY KEY (`grade_id`),
KEY `stdgrd_idx` (`student_id`),
CONSTRAINT `stdgrd` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1641 DEFAULT CHARSET=utf8;
I have created two tables student and grade. In order to send the auto-incremented values ofstudent_id to grade(student_id) table I established a foreign key between those two records as follows:
CONSTRAINT `stdgrd` FOREIGN KEY (`student_id`) REFERENCES `student`
(`student_id`) ON DELETE CASCADE ON UPDATE CASCADE
My question is when I insert values into student_name record in the student table the student(student_id) is auto-incremented so I want the auto-incremented value to be sent to grade(student_id)
but the grade table is not taking the value in. I already tried with the help of questions posted in stackoverflow but I couldn't make it. Please can anyone help out with this issue??
The Foreign Key relationship is only intended to validate the content of the child column. There is no automatic transfer of data. Inserting into student and thus generating the student_id auto_inc value will have no immediate impact on the grades table. That merely creates a student_id value that is now an acceptable content for the grades.student_id column.

Cannot delete or update a parent row

When I try and delete a movie from my database I get a the above error. I believe I have some how made the rated table have precedence over the films table.
How do I make the film table have precedence of the rated table
DELETE FROM `film`.`films` WHERE `films`.`movie_id` =16
--
-- Table structure for table `films`
--
CREATE TABLE IF NOT EXISTS `films` (
`movie_id` int(4) NOT NULL AUTO_INCREMENT,
`movie_title` varchar(100) NOT NULL,
`actor` varchar(100) NOT NULL,
PRIMARY KEY (`movie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `rated` (
`rated_id` int(4) NOT NULL AUTO_INCREMENT,
`rated_name` varchar(40) NOT NULL,
`movie_id` int(4) DEFAULT NULL,
PRIMARY KEY (`rated_id`),
KEY `movie_id` (`movie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
ALTER TABLE `rated`
ADD CONSTRAINT `rated_ibfk_1` FOREIGN KEY (`movie_id`) REFERENCES `films` (`movie_id`);
The foreign key you have defined on movie_id by default restricts the deletion: with the current schema you cannot delete a film as long as it has ratings.
You can automatically delete the ratings when you delete the film using cascading delete. Whether this is the best option for your application is for you to decide...
ALTER TABLE `rated` ADD FOREIGN KEY (`movie_id`)
REFERENCES `films` (`movie_id`) ON DELETE CASCADE;
Since there is a foreign key constraint you have to first delete any child records before you can delete the parent.
Try deleting everything from Rated table first, then deleting from films table.
DELETE FROM Rated
WHERE Movie_ID = 16
DELETE FROM Films
WHERE Movie_ID = 16

Foreign key doesn't keep data consistency

Many days ago I made a database which had two tables:
member(member_id(PK),name)
account(account_id(PK),member_id(FK),amount).
So Normally I cant DELETE any member if member have balance in account table . Before it was work well.
But today I import same script and I can delete a member even member have balance in account table.
I don't know what happends? I don't remember previous server version of mysql. Now I am running mysql 5.5.16 and MySQL client version is mysqlnd 5.0.8-dev - 20102224 - Revision: 310735 in localhost.
my code is
//account table
CREATE TABLE IF NOT EXISTS `account` (
`account_id` int(11) NOT NULL AUTO_INCREMENT,
`member_id` int(11) NOT NULL,
`dates` date NOT NULL,
`amount` float NOT NULL,
PRIMARY KEY (`account_id`),
KEY `FK_account_1` (`member_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
//member table
CREATE TABLE IF NOT EXISTS `member` (
`member_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`account_num` int(11) NOT NULL,
PRIMARY KEY (`member_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;
//and this code
ALTER TABLE `account`
ADD CONSTRAINT `FK_account_1`
FOREIGN KEY (`member_id`)
REFERENCES `member`(`member_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
I'm not sure if I understand this well but:
The constraint you have means that every time you delete a member, the member will be deleted together with any balance it has in the account table. (ON DELETE CASCADE)
If this is not your desired behavior, and you want mysql to raise an exception when deleting a member that has a balance; then just remove the ON DELETE CASCADE line from your constraint definition.
ALTER TABLE account
ADD CONSTRAINT `fk_account_member`
FOREIGN KEY (`member_id`)
REFERENCES `member` (`member_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;

how to define foreign key constraints

I have three mysql tables. Tables are already created.
Requests - request_id, request_message, user_id
Responses - response_id, response_message, user_id
users - user_id, user_name
Now i want to define foreign key constraints on that, such that
1. If user_id is not present in Users table, and someone is inserting the data in Requests or Responses for that user_id -- then error
2. If request_id is not present in Requests table, then if someone is inserting in responses table for that request_id -- then error
3. If someone deletes an user_id, all associated requests and responses with that user_id should be deleted automatically.
4. If someone deletes an request_id, all the associated responses with it, should be deleted automatically.
If i am missing any thing please let me know.
How to achieve this functionality?
Thanks
Devesh
Here is full sql to create your tables:
CREATE TABLE IF NOT EXISTS `reponses` (
`response_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`response_message` varchar(45) DEFAULT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`response_id`,`user_id`),
KEY `fk_reponses_users1` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `requests` (
`request_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`request_message` varchar(45) DEFAULT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`request_id`,`user_id`),
KEY `fk_requests_users` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;
ALTER TABLE `reponses`
ADD CONSTRAINT `reponses_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
ALTER TABLE `requests`
ADD CONSTRAINT `requests_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
Option that allows you to delete records related to user is ON DELETE CASCADE. By default MySql sets NO ACTION which refers to RESTRICT and doesn't allow parent record to be deleted while it has related objects. I think that you didn't mention the relation between responses and requests but you should get the idea ;).