简体   繁体   English

插入外键连接的表的查询

[英]Insert query for tables with connected in foreign key

Suppose I have following two tables with linked in foreign key address.假设我有以下两个表,其中链接了外键地址。 Assume a person can have different address.假设一个人可以有不同的地址。 So the table structure looks like following where for instance person aa have two addresses.所以表结构如下所示,例如人 aa 有两个地址。

table A表A

id name age adress
-------------------
1  aa   bb  10
2  xx   cc  11 

table B表 B

id adress lane1 lane2 lane3 
----------------------------
1  10     l2    l2    l3
2  10     v1    v2    v3

Please tell me how to write the sql insert statement where i can cover the scenario which person aa have two address.请告诉我如何编写 sql 插入语句,我可以在其中涵盖人 aa 有两个地址的情况。 (insert statement for populate data as i show in above tables) (插入填充数据的语句,如上表所示)

When you have circular foreign keys you need what PostgreSQL calls deferred constraints don't know if mysql has these.当您有循环外键时,您需要 PostgreSQL 所谓的延迟约束不知道 mysql 是否有这些。 But it is also a sign of bad schema design.但这也是架构设计不佳的标志。

Better structure would be:更好的结构是:

table person

id name age

1  aa   bb
2  xx   cc

table address

id person lane1 lane2 lane3 
1  1     l2    l2    l3
2  1     v1    v2    v3

Then you will need only one foreign-key and the inserts shouldn't give you any trouble.那么您将只需要一个外键,并且插入不会给您带来任何麻烦。

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

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