簡體   English   中英

如何在MySQL中將一個表與另一個表關聯(最好使用PHPMyAdmin)

[英]How to relate one table to another in MySQL (with PHPMyAdmin, preferably)

如何將一列與另一張表中的另一列關聯? 我會在另一個表中創建一個具有相同名稱的列嗎?

您需要建立外FOREIGN KEY關系。 在此示例中, Main_Table.idRelated.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM