SQL 同一列中有多个数据的数据库设计

SQL Database Design with more than one data in same column

我想创建一个数据库table,其中包含大量信息。这些信息之一是 phones。我如何创建一个数据库 table,在 phones 列内将包含子列,因为用户可能有多个 phone 并存储在同一行中相同的ID。

下面是我的意思以及我希望我的 table 成为...

不幸的是,所有答案都有帮助,我只能选择一个,但所有答案都对我有帮助

关系数据库中没有子列的概念。

如果您想为每个用户存储可变数量的 phone,一种解决方案是创建另一个 table 以将它们存储为 . phones table 应该有一个列来存储每个 phone 相关的用户 ID,并使用外键约束确保该列中包含的值确实存在于 users table.

所以:

users(id, name, address)
phones(id, user_id, phone_no)

Typical DDL (MySQL syntax):

create table users (
    id int primary key auto_increment,
    name varchar(50) not null,
    address varchar(50)
);

create table phones(
     id int primary key auto_increment,
     user_id int not null,
     phone_no varchar(20) not null,
     foreign key (user_id) references users(id)
);

你一般不会。您创建另一个 table。假设您有:

create table users (
    userId serial primary key,
    name varchar(255),
    . . .
);

然后你创建一个"junction"或"association" table:

create table userPhones (
     userPhoneId serial primary key,
     userId int references users(userId),
     phone varchar(32)
);

您没有指定数据库。我使用 serial 作为主键,因为它被 Postgres 使用并且易于输入。

这是一个 ER 流程,因为在您的案例中通过主键外键关系有一个 phoneid

       users(id (Pk), name, address, phoneid(fk))

       phones(userid(fk), phoneid (pk), phonenumber) 
       here userid and phoneid references users.phoneid and users.id

SQL Fiddle

MS SQL Server 2017 架构设置:

create table my_user (
    ID  int primary key,
    FirstName varchar(255),
    LastName varchar(255),
    address varchar(max)
)
create table user_phones (
     ID int primary key,
     userId int references my_user(ID),
     countrycode int,
     phone varchar(max),
     type varchar(255)
)
INSERT INTO my_user(ID,FirstName,LastName,address) VALUES(1,'test','test','test');
INSERT INTO user_phones(ID,userId,countrycode,phone,type)VALUES(1,1,99,'000099900','mobile');
INSERT INTO user_phones(ID,userId,countrycode,phone,type)VALUES(2,1,99,'99900000','home');
INSERT INTO user_phones(ID,userId,countrycode,phone,type)VALUES(3,1,99,'000009999','fax');

查询 1:

select * from my_user u
left join user_phones p on u.ID=p.userId

Results:

| ID | FirstName | LastName | address | ID | userId | countrycode |     phone |   type |
|----|-----------|----------|---------|----|--------|-------------|-----------|--------|
|  1 |      test |     test |    test |  1 |      1 |          99 | 000099900 | mobile |
|  1 |      test |     test |    test |  2 |      1 |          99 |  99900000 |   home |
|  1 |      test |     test |    test |  3 |      1 |          99 | 000009999 |    fax |