如何在我的sql数据库中存储一对多的关系? (MySQL的)

时间:2022-10-05 14:16:31

I'm making a website and I need to store a random number of data in my database.

我正在建立一个网站,我需要在我的数据库中存储随机数量的数据。

for example: User john may have one phone number where jack can have 3.

例如:用户john可能有一个电话号码,其中jack可以有3个。

I need to be able so store an infinite number of values per user.

我需要能够为每个用户存储无限数量的值。

I couldn't find how to do this anywhere, Hope you can help me! :)

我无法在任何地方找到这样做,希望你能帮助我! :)

I am a novice in Relational databases.

我是关系数据库的新手。

2 个解决方案

#1


22  

You create a separate table for phone numbers (i.e. a 1:M relationship).

您为电话号码创建一个单独的表(即1:M关系)。

create table `users` (
  `id` int unsigned not null auto_increment,
  `name` varchar(100) not null,
  primary key(`id`)
);

create table `phone_numbers` (
  `id` int unsigned not null auto_increment,
  `user_id` int unsigned not null,
  `phone_number` varchar(25) not null,
  index pn_user_index(`user_id`),
  foreign key (`user_id`) references users(`id`) on delete cascade,
  primary key(`id`)
);

Now you can, in an easily manner, get a users phone numbers with a simple join;

现在,您可以通过简单的连接轻松获取用户的电话号码;

select
  pn.`phone_number`
from
  `users` as u,
  `phone_numbers` as pn
where
  u.`name`='John'
  and
  pn.`user_id`=u.`id`

#2


0  

I think you need to create a one to many relationship table.

我认为你需要创建一对多的关系表。

You can see more infos here: http://dev.mysql.com/doc/workbench/en/wb-relationship-tools.html

您可以在此处查看更多信息:http://dev.mysql.com/doc/workbench/en/wb-relationship-tools.html

#1


22  

You create a separate table for phone numbers (i.e. a 1:M relationship).

您为电话号码创建一个单独的表(即1:M关系)。

create table `users` (
  `id` int unsigned not null auto_increment,
  `name` varchar(100) not null,
  primary key(`id`)
);

create table `phone_numbers` (
  `id` int unsigned not null auto_increment,
  `user_id` int unsigned not null,
  `phone_number` varchar(25) not null,
  index pn_user_index(`user_id`),
  foreign key (`user_id`) references users(`id`) on delete cascade,
  primary key(`id`)
);

Now you can, in an easily manner, get a users phone numbers with a simple join;

现在,您可以通过简单的连接轻松获取用户的电话号码;

select
  pn.`phone_number`
from
  `users` as u,
  `phone_numbers` as pn
where
  u.`name`='John'
  and
  pn.`user_id`=u.`id`

#2


0  

I think you need to create a one to many relationship table.

我认为你需要创建一对多的关系表。

You can see more infos here: http://dev.mysql.com/doc/workbench/en/wb-relationship-tools.html

您可以在此处查看更多信息:http://dev.mysql.com/doc/workbench/en/wb-relationship-tools.html