So I've got a table :
CREATE TABLE Commande
(
id_commande int NOT NULL AUTO_INCREMENT PRIMARY KEY,
client_id int,
livreur_id int,
plat_id int,
dessert_id int,
prix_total int,
heure_estime time,
FOREIGN KEY (client_id) REFERENCES Client(id_client),
FOREIGN KEY (livreur_id) REFERENCES Livreur(id_livreur),
FOREIGN KEY (plat_id) REFERENCES Plat(id_plat),
FOREIGN KEY (dessert_id) REFERENCES Dessert(id_dessert)
) ENGINE=InnoDB;
And in this table, I've got a plat_id and dessert_id, these means that each client can order a plat and a dessert, but I want it to be like each client can order multiple plat and multiple dessert and I don't know the quantity each client is going to order. How to do do this? I hope my question is explicit enough.
You're looking for a many-to-many relationship here. You can achieve that using a 'junction table' that relates every plate to every "commande". The table would have 2 foreign keys, one to the id_commande in the commande and one to plat_id in the Plat table. Thus, if the user with id_commande 1 eats two plates (1 and 2), you will be able to reflect that by adding 2 records to that table:
First record: id_commande: 1, plat_id: 1
Second record: id_commande: 1, plat_id: 2
You can add another table to relate the commande table with dessert as well.
Related
I want to know how to use a foreign key in a table,
I have a code here:
create table penerbit_buku(
id_buku char(8),
foreign key(id_buku) references buku(id_buku),
id_penerbit char(3),
foreign key(id_penerbit) references penerbit(id_penerbit)
)
Can I use this code instead:
create table penerbit_buku(
id_buku char(8) references buku(id_buku),
id_penerbit char(3) references penerbit(id_penerbit)
)
I have tried both and it succeed, is that correct?
No, MySQL parses but ignores the standard inline REFERENCES syntax.
When you declare a foreign key along with an individual column definition, it accepts the syntax as legitimate SQL, but then does not store the foreign key constraint. There's no error reported, but it's as if you didn't write the foreign key syntax at all.
You must declare foreign keys as table-level constraints (your first example above).
This is a case where MySQL is missing a feature of standard SQL. The issue was reported back in 2004, but never fixed! https://bugs.mysql.com/bug.php?id=4919
The reason for this issue is that historically, foreign key constraints were not supported by MySQL itself, but by the InnoDB storage engine, which was made by another company back then. They had to implement their own parser for CREATE TABLE and ALTER TABLE to support foreign keys, and they didn't feel like going the extra steps to support inline foreign key syntax, when table-level foreign key syntax would work.
The architect of InnoDB posted this response:
[6 Sep 2006 10:03] Heikki Tuuri
This will be fixed in MySQL foreign keys, when they are available for all table types.
The MySQL project is gradually working their way toward integrating foreign keys and similar features directly into the MySQL product. Perhaps in a few more years we'll see better support for standard FK syntax.
EXAMPLE:
CREATE TABLE Orders (
ID int NOT NULL,
Number int NOT NULL,
PersonID int,
PRIMARY KEY (ID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
The foreign key must be referencing a primary key in another table
create table penerbit_buku
(id_buku char(8),
id_penerbit char(3),
foreign key(id_buku) references buku(id_buku),
foreign key(id_penerbit) references penerbit(id_penerbit)
);
I would need to see your other tables to give better help in the code
You can use this:
ALTER TABLE `table1`
ADD CONSTRAINT `FK_table1_table2` FOREIGN KEY (`fk_id`) REFERENCES `table2` (`id`);
first lets look at the description of FOREIGN KEY.
A FOREIGN KEY is a key used to link two tables together.
or
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
Usually a table that has the foreign key is the child table. and the other table is the reference or parent table.
Since i Can not see your tables, ill give you different example.
Look at the following two tables:
Persons table:
Personal_id LastName FirstName age
1 pretty bob 20
2 angry jack 30
3 happy sue 28
Order Table:
OrderID OrderNumber Personal_id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Now look how Personal_id column in Orders table points to Personal_id in persons table.
The Personal_id in persons table is the primary key and the Personal_id in the orders table is the FOREIGN KEY.
now except linking how does foreign key help:
two general ways that i can think of:
1- foreign key is like a constrain that makes sure no action would destroy the links between tables
2- foreign key also acts as a constrain to stop invalid data from being inserted into the foreign key column, as it has to reference to the primary key column in the other table
code example in MySql:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (Personal_id) REFERENCES Persons(Personal_id)
);
code example is SQL-Server/MS Access/ Oracle:
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(Personal_id)
);
Primary key of Orders table is the orderID.
Foreign key of Orders table is what links it to persons table.
Personal_id columns are the columns that link both tables.
Both of the code chunks do the same depends what are you working with.
real world example:
assuming:
customer_Table column to be a primary key in restaurant table and foreign key in orders table.
if a waiter is putting customer_Table number 20 in the machine, and he puts customer_Table 200 by mistake such key does not exist as a primary key in restaurant table so he cant.
Extra:
what if you want to allow naming of the FOREIGN KEY constraint, and define a FOREIGN KEY constraint on many columns?
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
Personal_id int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (Personal_id)
REFERENCES Persons(Personal_id)
);
Im having some troubles with key referencing. The Error comes from when i try to insert data into Table Mark
INSERT INTO Mark(examID, studentID, result, occured, noOFAttempts)
VALUES ('B10', '1', '67', '11-JUL-07', '1');
I get the error:
integrity constraint violated - parent key
not found
Context :
The tables Exam and Student represent data about college exams and
students. The exam results for the students, including the number of
attempts a student has had at an exam (noOfAttempts), are recorded in
table Mark by using the id column from Exam and the id column from
Student. Both id columns have unique values . A student has only the
latest result recorded for each exam.
Write a SQL command to create the Mark table. Include the primary keys
and foreign keys apparent in the tables specified above.
CREATE TABLE Exam (
id VARCHAR(255),
subject VARCHAR(255),
noOfStudents INT,
PRIMARY KEY (id));
-
CREATE TABLE Student (
id INT,
name VARCHAR(255),
PRIMARY KEY (id));
-
CREATE TABLE Mark (
examID VARCHAR(255),
studentID INT,
result INT,
occured DATE,
noOFAttempts VARCHAR(255),
FOREIGN KEY (noOFAttempts) REFERENCES Exam(id),
FOREIGN KEY (noOFAttempts) REFERENCES Student(id));
How do i fix the error i know its to do with wrong referencing, thanks
Some of the logic behind the Mark table makes sense to me. It relates exams to the students who took those exams. But the motivation to make noOfAttempts a foreign key does not seem to serve much purpose. There are two foreign keys in that table, examID and studentID, and the combination of these two fields is also a primary key. Here is what the Mark definition might look like to avoid these errors:
CREATE TABLE Mark (
examID VARCHAR(255),
studentID INT,
result INT,
occured DATE,
noOFAttempts VARCHAR(255),
FOREIGN KEY (examID) REFERENCES Exam(id),
FOREIGN KEY (studentID) REFERENCES Student(id),
PRIMARY KEY (examID, studentID)
)
Again, I don't see the point of making noOfAttempts a key of any kind, rather I think it should just be one regular column in the Mark table.
Edit per request from Gordon:
When you made your insert, you attempted to create a record in Mark which referred to parent records which did not exist. In the case of your original table, you attempted to insert '1' as the noOfAttempts, but this ID did not exist in either the Exam and/or Student tables.
I have been trying to create a foregin key with nbrseats but I i get the error 1005 all the time.
CAn someone help me!?
create table theater (
name varchar(30) primary key,
nbrseats int not null
) ENGINE=INNODB;
create table reservation (
nbr integer auto_increment,
users_username varchar(30),
cinemashow_showdate date,
movies varchar(30),
nbrseats int not null,
primary key (nbr),
foreign key (nbrseats) references theater(nbrseats),
foreign key (users_username) REFERENCES users(username)
on delete cascade,
foreign key (cinemashow_showdate, movies) references cinemashow(showdate, movie_title)
on delete cascade
) ENGINE=INNODB;
In order to be a FOREIGN KEY in another table, you must have an index created on theater.nbrseats. And in order to be able to reference a specific row reliably, it should therefore be a UNIQUE index. Otherwise, if you have duplicate values, the referencing table won't be able to discern which row it references. Even though InnoDB will allow you to create the relationship on a non-unique index, it is likely not the behavior you are looking for.
See this question for more info on that bit.
create table theater (
name varchar(30) primary key,
nbrseats int not null,
UNIQUE INDEX `idx_nbrseats` (nbrseats)
) ENGINE=INNODB;
The same will be true of the other FOREIGN KEY definitions in your table reservation, though we do not see their referenced tables posted here. The rules are:
The referenced column must be indexed (independently of any other compound indexes on it)
The referencing column must have exactly the same data type.
This kind of calls into question your design, however. If you are attaching a number of seats to a reservation, will the reservation number of seats exactly match the number available in the theater? Also this means that you could not have 2 theaters with the same number of seats.
You may need to reconsider your design here, and perhaps create a FOREIGN KEY that references theater.name instead of theater.nbrseats.
project assignment is n to n relationship where n can be zero.
pid is primary key for the project table
eid is primary key for the employee table
a project may not be assigned to any employee.similary an employee may not have any project in his hand.
how to write this query? eid should take value as null or the value from the emp table.
pid should either take null or the value from the table project.
IS IT CORRECT.
CREATE TABLE Proj_Assign
(
eid VARCHAR(25),
pid VARCHAR(25),
PRIMARY KEY(eid,pid),
FOREIGN KEY eid REFERENCES employee(eid),
FOREIGN KEY pid REFERENCES project(pid)
);
Give this way:
FOREIGN KEY (t_eid) REFERENCES parent(eid)
ON DELETE CASCADE
Instead of using same eid twice. It is explained in the documentation.
Also, the original parent table should be there before you create this table and you need to manually insert the queries this way:
INSERT INTO `Proj_Assign` (`eid`, `pid`) VALUES (1, 1);
Whatever query you have written is right as per documentation.
Doing my first tryouts with foreign keys in a mySQL database and are trying to do a insert, that fails for this reason: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
Does this mean that foreign keys restrict INSERTS as well as DELETES and/or UPDATES on each table that is enforced with foreign keys relations?
Thanks!
Updated description:
Products
----------------------------
id | type
----------------------------
0 | 0
1 | 3
ProductsToCategories
----------------------------
productid | categoryid
----------------------------
0 | 0
1 | 1
Product table has following structure
CREATE TABLE IF NOT EXISTS `alpha`.`products` (
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`type` TINYINT(2) UNSIGNED NOT NULL DEFAULT 0 ,
PRIMARY KEY (`id`) ,
CONSTRAINT `funkyfunky`
FOREIGN KEY (`id` )
REFERENCES `alpha`.`ProductsToCategories` (`productid` )
ON DELETE CASCADE,
ON UPDATE CASCADE)
ENGINE = InnoDB;
Your insert is failing because the foreign key in the row you are inserting doesn't match a valid key in the constraint table. For example:
Assume you've got these two tables:
Employees
----------------------------
EmpID | Name
----------------------------
0 | John
1 | Jane
OfficeAssignments
----------------------------
OfficeID | EmpID
----------------------------
0 | 0
1 | 1
If you have a foreign key constraint on OfficeAssignments.EmpID -> Employees.EmpID, and you try to execute:
INSERT INTO OfficeAssignments (OfficeID, EmpID) VALUES (2,2)
The statement will fail because there is no entry in the Employees table with an EmpID of 2.
Constraints are designed to ensure that your dependent table always has valid data with regard to the parent table -- in this example, you will never have an office which is listed as assigned to an employee who doesn't exist in the system, either because they never existed (as in this case) or because they've been deleted (because the constraint will prevent the employee record from being deleted until the office assignment record has been deleted first).
Edit: Now that you've posted the constraint, it indeed looks like it might be set up backwards. By placing the constraint in the definition of the Products table, you are making it the child, and ProductsToCategories the parent. The constraint you've written can be read as, "a Product must be assigned to a category before it can be created". I suspect what you meant is the other way around: "a Product must be created before it can be assigned to a category." To get that result, you need to place the constraint on the ProductsToCategories table, setting the foreign key to productid and referencing Products.id.
You cannot delete a row from the parent table while there is a foreign key reference to it from a child table. Also you cannot insert/update in the child table with invalid id's in the foreign key column.
Edit: The "CONSTRAINT funkyfunky FOREIGN KEY (id)" must be declared in the "ProductsToCategories" table not in the "Products" table, because "ProductsToCategories" is referencing "Products" not the opposite as you have did.
Your products table is slightly wrong, as you don't need to reference anything from it. References go in the "other" tables, and point to the main, e.g:
create table products (
id int auto_increment,
type int,
primary key (id)
);
create table categories (
id int auto_increment,
name varchar(128),
primary key (id)
)
create table products_to_categories (
product_id int references products,
category_id int references categories
);
A foreign key enforces a valid relation between the rows in two tables. In order to be able to insert a row into a table containing a foreign key, there must be a row in the referenced table containing that key or the insert will fail. The same with delete, you can't delete the row in the referenced table while there are still rows in the table with the foreign key that still reference it. The prevents ending up with rows in the dependent table that have data, but don't have associated rows in the referenced table, i.e., a violation of referential integrity.