数据库中的多值属性 [英] multivalued attributes in databases

查看:2772
本文介绍了数据库中的多值属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设计关系数据库来处理多值属性?

How should a relational database be designed to handle multi-valued attributes ?

编辑:详细说明:

有两种方法可以想到这样做 -

There are two ways I could think of for doing this -


  1. 尝试使用逗号分隔值在现场看起来有点笨拙。

  2. 为该字段创建另一个表,让多个值进入该字段。这可能会导致非常多的表格,如果我有太多这样的字段。

问题是:


  1. 有没有更多的方法来处理?

  2. 通常使用上述两种方法中的哪一种? / li>
  1. Are there any more ways of handling this?
  2. Which of the above two methods is generally used?

提前感谢

推荐答案

在传统的关系数据库设计中,列必须只存储一个值。

In conventional relational database design, each row & column must store only one value.

不要存储逗号分隔的列表或任何类似的东西。

Don't store comma-separated lists or anything wacky like that.

例如,说一个运动团队有七名成员。您可以这样做:

For example, say a sports team has seven members. You could do this:

CREATE TABLE team (
  team_id      INT PRIMARY KEY,
  team_name    VARCHAR(50),
  team_members VARCHAR(200)
);
INSERT INTO team VALUES ('Dwarfs', 'Sleepy,Dopey,Sneezy,Happy,Grumpy,Doc,Bashful')

但是最好这样做:

CREATE TABLE team (
  team_id      INT PRIMARY KEY,
  team_name    VARCHAR(50),
);
INSERT INTO team (team_name) VALUES ('Dwarfs');

CREATE TABLE team_members (
  team_id      INT,
  member_name  VARCHAR(20),
  FOREIGN KEY (team_id) REFERENCES team(team_id)
);
INSERT INTO team_members VALUES 
  (LAST_INSERT_ID(), 'Sleepy'),
  (LAST_INSERT_ID(), 'Dopey'),
  (LAST_INSERT_ID(), 'Sneezy'),
  (LAST_INSERT_ID(), 'Happy'),
  (LAST_INSERT_ID(), 'Grumpy'),
  (LAST_INSERT_ID(), 'Doc'),
  (LAST_INSERT_ID(), 'Bashful');

nb: LAST_INSERT_ID()是一个MySQL函数。其他品牌的数据库也提供类似的解决方案。

nb: LAST_INSERT_ID() is a MySQL function. Similar solutions are available in other brands of database.

这篇关于数据库中的多值属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆