mysql多值属性表_数据库中的多值属性

bd96500e110b49cbb3cd949968f18be7.png

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

edit: To elaborate:

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

Trying something like putting comma separated values in the field, which appears a bit clumsy.

Create another table for the field and let the multiple values go to the field. This might lead to very large number of tables, if I have too many fields of this kind.

The question is:

Are there any more ways of handling this?

Which of the above two methods is generally used?

Thanks in advance

解决方案

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')

But it's better to do this:

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() is a MySQL function. Similar solutions are available in other brands of database.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值