[英]How to relate one table to another in MySQL (with PHPMyAdmin, preferably)
如何將一列與另一張表中的另一列關聯? 我會在另一個表中創建一個具有相同名稱的列嗎?
您需要建立外FOREIGN KEY
關系。 在此示例中, Main_Table.id
在Related.main_table_id
作為外鍵Related.main_table_id
Main_Table:
----------
id INT NOT NULL AUTO_INCREMENT,
value1 VARCHAR(8),
value2 VARCHAR(8)
Related:
---------
id INT NOT NULL AUTO_INCREMENT,
-- The related column doesn't have to have the same name
-- This column references Main_Table
main_table_id INT NOT NULL
-- The FOREIGN KEY constraint enforces the relationship
FOREIGN KEY (main_table_id) REFERENCES Main_Table (id)
此外,您可以通過刪除和更新來加強密鑰關系。 如果Main_Table
的行被刪除或其id
更改,則可以強制更改在相關表中級聯:
FOREIGN KEY (main_table_id) REFERENCES Main_Table (id) ON DELETE CASCADE ON UPDATE CASCADE
-- Or NULL it rather than delete it
FOREIGN KEY (main_table_id) REFERENCES Main_Table (id) ON DELETE SET NULL ON UPDATE CASCADE
您想要的功能稱為外鍵。 為此,數據庫不會使用列名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.