简体   繁体   English

如何在MySQL数据库中添加单个用户的多个地址

[英]How can I add multiple addresses of single user in MySQL database

i need help. 我需要帮助。 I want to have two tables in database. 我想在数据库中有两个表。 One is USER n othetis ADDRESS. 一种是用户密码。 I want to add multiple addresses for the user that is added in USER table. 我想为在USER表中添加的用户添加多个地址。 How can i do this ? 我怎样才能做到这一点 ? Thank you. 谢谢。

1st : You can add user unique id in address table . 第一:您可以在地址表中添加用户唯一ID。

2nd : And also maintain auto_increment primary key in address table why means when your going to edit the address means you need to update the right one so it's useful in future so maintain one column for that . 第二个问题:还要在地址表中维护auto_increment主键,这意味着为什么当您要编辑地址时意味着您需要更新正确的主键,因此在将来很有用,因此为此保留一列。

You Have two different tables: 您有两个不同的表:

1) USER 1)用户

2) ADDRESS 2)地址

Give foreign key for ID of user table to address table 将用户表ID的外键提供给地址表

Example: 例:

USER 用户

id    name    email
1     abc     xxx@xxx.com

ADDRESS 地址

id    user_id      address detail
1      1          address detail 1
2      1          address detail 2

Here user 1 has 2 address. 用户1在这里有2个地址。 You can add more address also 您也可以添加更多地址

According to the my opinion its just simple. 根据我的观点,这很简单。 Its one to many relationship of two tables. 它是两个表的一对多关系。 you can set user id as a foreign key of address table and add addresses. 您可以将用户ID设置为地址表的外键并添加地址。 user id is the primary key of user table. 用户ID是用户表的主键。

The ADDRESS table should have a many-to-one relationship with the USER table and contain USER_ID as a foreign key. ADDRESS表应与USER表具有多对一关系,并包含USER_ID作为外键。 Simply create multiple ADDRESS records that all have the same USER_ID. 只需创建多个具有相同USER_ID的ADDRESS记录。 To differentiate them you should add a field to specify the type of address such as home, business, etc. 为了区分它们,您应该添加一个字段以指定地址类型,例如家庭,公司等。

USER
ID, NAME, ...

ADDRESS
ID, USER_ID, ADDRESS_TYPE, STREET, ...

You should also really create separate tables for ADDRESS_TYPE, CITY, COUNTRY, STATE, etc. to avoid unnecessarily duplicated data and the problems that occur when those fields are allowed to be just entered as text - eg Montreal, montreal, MONTREAL, mtl, Montréal are all valid ways people write the same city. 您还应该真正为ADDRESS_TYPE,CITY,COUNTRY,STATE等创建单独的表,以避免不必要的重复数据以及避免仅允许将这些字段作为文本输入时发生的问题-例如,蒙特利尔,蒙特利尔,MONTREAL,mtl,蒙特利尔是人们写同一座城市的所有有效方法。

您只需要创建一个称为ADDRESS的表:

CREATE TABLE ADDRESS(id int not null,user_id int,address varchar(255),PRIMARY KEY (id),FOREIGN KEY (user_id) REFERENCES USER(user_id));

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

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