Is there any difference in declaring foreign keys on tables between this two options?
OPTION 1
create table Table1 (
name varchar(255),
id_fkey int references Table2 (id)
);
OPTION 2
create table Table1 (
name varchar(255),
id_fkey int,
foreign key (id_fkey) references Table2 (id)
);
Are both declarations of a proper foreign key or do they have any difference?
These are two ways to do the same thing. The first syntax is called column constraint, the second table constraint.
The only real difference is that a foreign key over more than one column can only be written as a table constraint.
Related
I would like to create a table that has multiple foreign keys to multiple different tables (as the relationship is many to many).
#creating t1
CREATE TABLE t1
(ID INT AUTO_INCREMENT primary key,
x1 VARCHAR(50)
);
#Creating t2
CREATE TABLE t2
(v1 VARCHAR(50),
v2 VARCHAR(50),
primary key (v1, v2)
);
#creating attended table
CREATE TABLE t3
(ID INT,
v1 VARCHAR(50),
v2 VARCHAR(50),
primary key (ID, v1, v2 ),
foreign key(v1) references t2(v1),
foreign key(v2) references t2(v2),
foreign key(ID) references t1(ID)
);
Above is my code. I get no errors for creating t1 and t2. However, I get the following code when I try to create t3:
ERROR 1215 (HY000): Cannot add foreign key constraint
The foreign key is the complete key of the other table - you can not only use half of it as FK.
t2 has a combined primary key. when referencing a fk in t3 you need both.
See Why use multiple columns as primary keys (composite primary key)
To create a complex FK see SQL Server: adding foreign key on multiple columns
or for MySql see Multiple-column foreign key in MySQL?
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)
);
I have 2 tables here for example table A and table B, how can i insert data when both of the tables consist of foreign key of each other? like table A got an attribute is foreign key references of table B, and table B got an attribute is foreign key references of table A
create table abc
(ID varchar(10),
subID varchar(10),
primary key (ID),
foreign key (subID) references def(SubID)
)
create table def
(SubID varchar(10),
ID varchar(10),
primary key (SubID),
foreign key (ID) references abc(ID)
)
somehow like this(i skipped other various informations)
I don't think it will be possible in your current design.
If you really have the need to do insert with cross dependency over the two tables, remove the one foreign key. Then you can do an insert on table ABC and then DEF.
I also think your DB design is incorrect.
I want to create 2 tables in MySQL where the second table has a foreign key from my base table.
The problem is when I try to create the second table I get errno:150. Which fails because the foreign keys are null.
How can I create the second table properly?
More details
My first table has 5 attributes and the first attribute is the Primary key.
My second table has 3 attributes. The 1st and 2nd attribute of this table reference the first 2 attributes from the first table.
All the variables are varchar and all are same length. Any suggestions?
I think the proper way to fix this, given that we can't see your code, would be on MySQL - Foreign Key documentation page.
See their example below:
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
This line is precisely what you need to do : FOREIGN KEY (parent_id) REFERENCES parent(id).
my problem is that i have to make table which will have foreign keys, and one of three foreign keys have to be NOT NULL and rest have to be NULL.
Is there anything in MySQL to solve it?
Michael.
Avoid nullable foreign keys - they have a number of problems and disadvantages. It's generally easier and better to put those columns in separate tables so that you don't have to create nulls for them when no value exists. That ought to be the default approach: Normal Form for each distinct case unless you have some special reason to combine the three columns into one table.
FOREIGN KEY Constraints example:
CREATE TABLE parent
(
id INT NOT NULL, PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child
(
id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
) ENGINE=INNODB;