I have multiple tables and I want multiple foreign keys.
Users Table
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| idUsers | int(11) | NO | PRI | NULL | |
| Username | varchar(45) | YES | | NULL | |
| Password | varchar(45) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
Friends Table
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| idUser | int(11) | YES | MUL | NULL | |
| idFriend | int(11) | YES | MUL | NULL | |
| Status | varchar(45) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
Groups Table
+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| idGroup | int(11) | NO | PRI | NULL | |
| GroupName | varchar(45) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
Members Table
+----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| idGroup | int(11) | YES | MUL | NULL | |
| idMember | int(11) | YES | MUL | NULL | |
+----------+---------+------+-----+---------+-------+
This is the foreign key for my Members Table so that the idGroup and idMember both correspond to the Users table idUsers.
ALTER TABLE `GroupOrder`.`Friends`
ADD CONSTRAINT `idFriend`
FOREIGN KEY (`idFriend`)
REFERENCES `GroupOrder`.`Users` (`idUsers`)
ON DELETE CASCADE
ON UPDATE CASCADE;
I want to make another foreign key in the Friends table that corresponds to the Users table. Am I'm doing in wrong. Everytime I do this I get an error.
ALTER TABLE `GroupOrder`.`Friends`
ADD CONSTRAINT `idFriend`
FOREIGN KEY (`idUser` , `idFriend`)
REFERENCES `GroupOrder`.`Users` (`idUsers` , `idUsers`)
ON DELETE CASCADE
ON UPDATE CASCADE;
Error
ERROR 1005: Can't create table 'GroupOrder.#sql-2fce_1e' (errno: 150)
SQL Statement:
ALTER TABLE `GroupOrder`.`Friends`
ADD CONSTRAINT `idFriend`
FOREIGN KEY (`idUser` , `idFriend`)
REFERENCES `GroupOrder`.`Users` (`idUsers` , `idUsers`)
ON DELETE CASCADE
ON UPDATE CASCADE
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'Friends' already exists
SQL Statement:
CREATE TABLE `Friends` (
`idUser` int(11) DEFAULT NULL,
`idFriend` int(11) DEFAULT NULL,
`Status` varchar(45) DEFAULT NULL,
KEY `idUser_idx` (`idFriend`),
KEY `idUser_idx1` (`idUser`,`idFriend`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I am assuming friends is a many to many mapping from users to users. This sort of implies friendship can be one-way, but that isn't necessarily wrong.
You already mapped idfriend in friends to idusers in users, now map iduser in friends to idusers in users.
ALTER TABLE `GroupOrder`.`Friends`
ADD CONSTRAINT `idFriend2`
FOREIGN KEY (`idUser`)
REFERENCES `GroupOrder`.`Users` (`idUsers`)
ON DELETE CASCADE
ON UPDATE CASCADE;
Now, you probably want to enforce uniqueness of iduser and idfriend in friends so you don't have repetition.
alter table `grouporder`.friends`
add unique(oduser, idfriend);
Related
The first table is LocationTime table and the second table is Student table.
I am adding a Foreign Key using 'ALTER'. But I got the error below. Why am I getting the error?
Cannot add foreign key constraint Error
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| CourseN | varchar(3) | NO | PRI | NULL | |
| Quarter | varchar(11) | NO | PRI | NULL | |
| DayTime | varchar(7) | NO | PRI | NULL | |
| RoomN | varchar(3) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| studentName | varchar(15) | NO | PRI | NULL | |
| CourseN | varchar(3) | NO | PRI | NULL | |
| Quarter | varchar(11) | NO | PRI | NULL | |
+-------------+-------------+------+-----+---------+-------+
ALTER TABLE Student
ADD FOREIGN KEY (Quarter) REFERENCES LocationTime (Quarter)
ON UPDATE CASCADE ON DELETE SET NULL;
The problem is the fact that Quarter is a member of a composite key (CouresN, Quarter and DayTime forms the primary key for the LocationTime table). It is not possible to declare a Foreign Key Constraint on another table that is associated only with the Quarter, it should also include the other parts of the composite key. One possible solution to your problem it would be to declare other columns as your primary keys. Furthermore, I don't see the reason why you don't use a column with a auto generated INT (IDENTITY) as you primary key, or a column with an auto generated GUID.
If you are trying to INSERT a value into the table table_1 that does not exist in the table table_2 then you will get the error.
Since you have a Foreign Key on the table_1 field, you have to have the same value in the table_2.
See a non-working demo. This demo shows that the value for Codigo does not exist in the Fabricantes table so it throws the error message. Here is a working demo which shows that the value is in the table first.
I am trying to create relation between two tables. My table names are employees and salaries. I tried the following code:
ALTER TABLE `salaries`
ADD FOREIGN KEY (`eid`)
REFERENCES `employees`(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
But it shows an error:
Error creating foreign key on eid (check data types)
employees table structure:
+---------------------------------------+
| id | int(11) | primary |
|--------------+--------------+---------|
| name | varchar(255) | unique |
|--------------+--------------+---------|
| basic | int(11) | |
|--------------+--------------+---------|
| ot_rate | int(11) | |
|--------------+--------------+---------|
| joining_date | date | |
+---------------------------------------+
salaries Table Structure:
+---------------------------------------+
| id | int(11) | primary |
|--------------+--------------+---------|
| eid | int(11) | index | <-- I want to create foreign key on this column with employees->id.
|--------------+--------------+---------|
| month | varchar(255) | |
|--------------+--------------+---------|
| date | date | |
|--------------+--------------+---------|
| working_day | int(11) | |
+--------------+--------------+---------+
| ot_hour | int(11) | |
|--------------+--------------+---------|
| ot_amount | int(11) | |
|--------------+--------------+---------|
| basic_amount | int(11) | |
|--------------+--------------+---------|
| tatal_salary | inf(11) | |
|--------------+--------------+---------|
| comment | varchar(255) | |
+---------------------------------------+
I tried changing eid's data type to varchar,tinyint,text etc. All has the same error message.
UPDATE
After using this:
ALTER TABLE `salaries`
ADD CONSTRAINT `salary` FOREIGN KEY (`eid`)
REFERENCES `employees`(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
I am having this error message:
#1005 - Can't create table `zamzam`.`#sql-14b4_1a5` (errno: 150 "Foreign key constraint is incorrectly formed")
Have you used the relational view option in the table to create the foreign key contraint .
this link will show you the way -http://www.binarytides.com/create-foreign-key-phpmyadmin/
thanks
mysql> DESCRIBE questions;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(255) | NO | PRI | NULL | auto_increment |
| question | varchar(255) | NO | | NULL | |
| type | char(1) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
mysql> DESCRIBE answers;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(255) | NO | PRI | NULL | auto_increment |
| answer | varchar(255) | NO | | NULL | |
| questionid | int(255) | NO | | NULL | |
| questions_id | int(255) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
I am using this statement:
ALTER TABLE answers ADD FOREIGN KEY(questions_id) REFERENCES questions(id);
but i get this error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (surveydb.#sql-df_32, CONSTRAINT #sql-df_32_ibfk_1 FOREIGN KEY (questions_id) REFERENCES questions (id))to your MySQL server version for the right syntax to use near 'DESCREBE questions' at line 1
You have at least one data value in answers.questions_id that does not occur in questions.id.
Here's an example of what I mean:
mysql> create table a ( id int primary key);
mysql> create table b ( aid int );
mysql> insert into a values (123);
mysql> insert into b values (123), (456);
mysql> alter table b add foreign key (aid) references a(id);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint
fails (`test`.`#sql-3dab_e5c`, CONSTRAINT `#sql-3dab_e5c_ibfk_1` FOREIGN KEY
(`aid`) REFERENCES `a` (`id`))
You can use this to confirm that there are unmatched values:
SELECT COUNT(*)
FROM answers AS a
LEFT OUTER JOIN questions AS q ON a.questions_id = q.id
WHERE q.id IS NULL
I have the tables Players and PlayerMeta
mysql> DESCRIBE Players;
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| ID | int(5) | NO | PRI | NULL | auto_increment |
| PlayerName | varchar(20) | NO | PRI | NULL | |
| Birthdate | date | YES | | NULL | |
| Location | varchar(20) | YES | | NULL | |
| FirstName | varchar(15) | YES | | NULL | |
| Whitelisted | tinyint(1) | NO | | 1 | |
+-------------+-------------+------+-----+---------+----------------+
mysql> DESCRIBE PlayerMeta;
+----------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------+------+-----+---------+-------+
| ID | int(5) | NO | PRI | NULL | |
| JoinDate | date | YES | | NULL | |
| BuildQuota | int(2) | NO | | 2 | |
| RegisteredDate | date | YES | | NULL | |
| HideBirthdate | tinyint(1) | NO | | 0 | |
+----------------+------------+------+-----+---------+-------+
I am trying to execute this command, and it returns Query OK:
ALTER TABLE PlayerMeta
ADD CONSTRAINT fk_PlayerID
FOREIGN KEY (ID)
REFERENCES Players(ID)
ON UPDATE CASCADE
ON DELETE CASCADE;
Yet, when I run SHOW CREATE TABLE PlayerMeta, it does not show the constraint, nor is it in INFORMATION_SCHEMA
Any thoughts? Thanks.
EDIT: Here is SHOW CREATE TABLE PlayerMeta:
mysql> SHOW CREATE TABLE PlayerMeta;
... a bunch of lines ...
| PlayerMeta | CREATE TABLE `PlayerMeta` (
`ID` int(5) NOT NULL,
`JoinDate` date DEFAULT NULL,
`BuildQuota` int(2) NOT NULL DEFAULT '2',
`RegisteredDate` date DEFAULT NULL,
`HideBirthdate` tinyint(1) NOT NULL DEFAULT '0',
UNIQUE KEY `ID` (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
EDIT(2): The problem was ID in PlayerMeta was already a primary key and a foreign key would not apply in conjunction with it.
You cannot create foreign keys for MyISAM.
Only InnoDB supports them.
So the solution for you is to change the storage engine for both tables.
ALTER TABLE Players ENGINE=InnoDB;
ALTER TABLE PlayerMeta ENGINE=InnoDB;
Then re-apply your ALTER with adding a FK constraint.
MySQL will not permit you to create a FOREIGN KEY constraint on a column which is itself a PRIMARY KEY. If your design is such that the two tables share a one-to-one relationship and both hold information about a Player, it may not make sense to separate them and instead combine both tables into one.
In any case, if you wish to keep them separate and enforce a FOREIGN KEY relationship on them, you need to remove the PRIMARY KEY on PlayerMeta.ID. You may still have a UNIQUE, non primary key index on it.
mysql> DESCRIBE questions;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(255) | NO | PRI | NULL | auto_increment |
| question | varchar(255) | NO | | NULL | |
| type | char(1) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
mysql> DESCRIBE answers;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(255) | NO | PRI | NULL | auto_increment |
| answer | varchar(255) | NO | | NULL | |
| questionid | int(255) | NO | | NULL | |
| questions_id | int(255) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
I am using this statement:
ALTER TABLE answers ADD FOREIGN KEY(questions_id) REFERENCES questions(id);
but i get this error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (surveydb.#sql-df_32, CONSTRAINT #sql-df_32_ibfk_1 FOREIGN KEY (questions_id) REFERENCES questions (id))to your MySQL server version for the right syntax to use near 'DESCREBE questions' at line 1
You have at least one data value in answers.questions_id that does not occur in questions.id.
Here's an example of what I mean:
mysql> create table a ( id int primary key);
mysql> create table b ( aid int );
mysql> insert into a values (123);
mysql> insert into b values (123), (456);
mysql> alter table b add foreign key (aid) references a(id);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint
fails (`test`.`#sql-3dab_e5c`, CONSTRAINT `#sql-3dab_e5c_ibfk_1` FOREIGN KEY
(`aid`) REFERENCES `a` (`id`))
You can use this to confirm that there are unmatched values:
SELECT COUNT(*)
FROM answers AS a
LEFT OUTER JOIN questions AS q ON a.questions_id = q.id
WHERE q.id IS NULL