Kekurangan FOREIGN KEY SQL
- Halaman Sebelumnya Kunci Utama SQL
- Halaman Berikutnya SQL Check
Kekurangan FOREIGN KEY SQL
FOREIGN KEY di tabel satu menunjuk ke PRIMARY KEY di tabel lain.
Kami akan menjelaskan FOREIGN KEY melalui contoh. Lihat tabel berikut ini:
Tabel "Persons":
Id_P | LastName | FirstName | Alamat | City |
---|---|---|---|---|
1 | Adams | John | Oxford Street | London |
2 | Bush | George | Fifth Avenue | New York |
3 | Carter | Thomas | Changan Street | Beijing |
Tabel "Orders":
Id_O | OrderNo | Id_P |
---|---|---|
1 | 77895 | 3 |
2 | 44678 | 3 |
3 | 22456 | 1 |
4 | 24562 | 1 |
Perhatikan bahwa kolom "Id_P" di "Orders" menunjuk ke kolom "Id_P" di tabel "Persons".
Kolom "Id_P" di tabel "Persons" adalah PRIMARY KEY di tabel "Persons".
Kolom "Id_P" di tabel "Orders" adalah FOREIGN KEY di tabel "Orders".
Constraint FOREIGN KEY digunakan untuk mencegah aksi yang menghancurkan koneksi antar tabel.
Constraint FOREIGN KEY juga dapat mencegah pengecekan data ilegal yang dimasukkan ke kolom referensi, karena harus menjadi salah satu nilai di tabel yang ditujukan.
Constraint FOREIGN KEY dalam CREATE TABLE
Berikut adalah SQL untuk membuat FOREIGN KEY untuk kolom "Id_P" saat tabel "Orders" dibuat:
MySQL:
CREATE TABLE Orders ( Id_O int NOT NULL, OrderNo int NOT NULL, Id_P int, Kunci Utama (Id_O), FOREIGN KEY (Id_P) REFERENCES Persons(Id_P) )
SQL Server / Oracle / MS Access:
CREATE TABLE Orders ( Id_O int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, Id_P int FOREIGN KEY REFERENCES Persons(Id_P) )
Jika perlu menamakan CONSTRAINT FOREIGN KEY serta mendefinisikan CONSTRAINT FOREIGN KEY untuk beberapa kolom, gunakan syntax SQL di bawah ini:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders ( Id_O int NOT NULL, OrderNo int NOT NULL, Id_P int, Kunci Utama (Id_O), CONSTRAINT fk_PerOrders FOREIGN KEY (Id_P) REFERENCES Persons(Id_P) )
Constraint FOREIGN KEY SQL di ALTER TABLE
Jika membuat CONSTRAINT FOREIGN KEY untuk kolom "Id_P" saat tabel "Orders" sudah ada, gunakan SQL di bawah ini:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders ADD FOREIGN KEY (Id_P) REFERENCES Persons(Id_P)
Jika perlu menamakan CONSTRAINT FOREIGN KEY serta mendefinisikan CONSTRAINT FOREIGN KEY untuk beberapa kolom, gunakan syntax SQL di bawah ini:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (Id_P) REFERENCES Persons(Id_P)
Hapus CONSTRAINT FOREIGN KEY
Untuk menghapus CONSTRAINT FOREIGN KEY, gunakan SQL di bawah ini:
MySQL:
ALTER TABLE Orders DROP FOREIGN KEY fk_PerOrders
SQL Server / Oracle / MS Access:
ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders
- Halaman Sebelumnya Kunci Utama SQL
- Halaman Berikutnya SQL Check