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.
Related
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.
Misson:
I'm trying to create two tables in MySQL, the first table has two primary keys (composite). The second table has three, two of which are foreign keys that reference the first tables two primary keys. So now I'm trying to bridge them, which isolates the problem code and can be seen below.
Issue:
MySQL workbench refuses allow me to create a table that references another table's two primary keys. It just gives me the error code: 1215. Cannot add foreign key constraint.
I tried:
Changing the attribute types from datetime to varchar(). Changing the attribute names. Checked spelling 5 times. Referencing only one key works fine, but I need both.
Problem Code (SQL Table):
CREATE TABLE IF NOT EXISTS TestInformation2
(
WorkOrder varchar(15),
Date datetime,
TechnicianID smallint,
Primary key (WorkOrder, Date)
) ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS TestBridge2
(
TestBridgeID integer Primary key,
WorkOrder varchar(15),
Date datetime,
Foreign key (WorkOrder) references TestInformation (WorkOrder),
Foreign key (Date) references TestInformation (Date)
) ENGINE = InnoDB;
Result I want:
Create the table 'TestBridge' which has the two foreign key attributes: WorkOrder and Date
It should be one composite foreign key, not two:
CREATE TABLE `TestBridge2` (
`TestBridgeID` INTEGER NOT NULL,
`WorkOrder` VARCHAR(15),
`Date` DATETIME,
PRIMARY KEY (`TestBridgeID`),
CONSTRAINT FOREIGN KEY (`WorkOrder`, `Date`) REFERENCES `TestInformation2` (`WorkOrder`, `Date`)
)
ENGINE=InnoDB;
One single foreign key has to be created for this like:
CREATE TABLE IF NOT EXISTS TestBridge2
(
TestBridgeID integer Primary key,
WorkOrder varchar(15),
Date datetime,
Foreign key (WorkOrder, Date) references TestInformation2 (WorkOrder, Date)
) ENGINE = InnoDB;
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 want to create two tables, one is having primary key and other for foreign key.
So my requirement is the values in users should be available which are present only in customers table other vice show error constraint violation.
Did something like this, but still am able to insert values in users which are not in customers.
create table if not exists customers
(
cust_user_id int,
primary key (cust_user_id)
);
create table if not exists users
( prid INT,
foreign key (prid) references customers(cust_user_id) ON UPDATE CASCADE
);
Any suggestion ?
Thanks
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).