简体   繁体   English

将两个相同的外键从同一个表转换为另一个表?

[英]Two of the same foreign key from the same table into another table?

Is it ok to have two columns in a table that can be a foreign key from the same table? 可以在一个表中有两列可以是同一表的外键吗?

For example: 例如:

I have an 'address' table with columns: 我有一个带有列的“地址”表:
id, street, city_id, state, country (or id, street, city_id, state_id, state_id) id,街道,city_id,州,国家(或id,街道,city_id,state_id,state_id)

I have a 'states' table that hold state and countries: id, name, level 我有一个包含州和国家/地区的“州”表:ID,名称,级别

So can I put states_id in state and country of the address table (as in the brackets above)? 那么我可以将states_id放在地址表的州和国家/地区中吗(如上面的括号所示)?

Yes, that's totally OK. 是的,那完全可以。

Ed Gibbs's is right, don't do that if the state implies the country. 埃德·吉布斯(Ed Gibbs)的观点是正确的,如果国家暗示国家,那就不要这样做。

In your exemple, maybe it would be better to split the table in two distinct tables for clarity, say State and Country , but from a general point of view, there's no problem with this practice. 在您的例子中,为了清楚起见,最好将表分为两个不同的表,例如StateCountry ,但是从一般的角度来看,这种做法没有问题。

This case (2 FK in a table both referencing another table) often happens, for example in a messages table, with a sender and a receiver , which both would reference to the same users table. 这种情况(表中的2 FK都引用另一个表)经常发生,例如在messages表中,同时具有senderreceiver ,这两个senderreceiver都引用同一users表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM