multivalued attributes in databases

前端 未结 5 932
甜味超标
甜味超标 2021-02-03 11:47

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

edit: To elaborate:

There are two ways I could think of for do

5条回答
  •  情深已故
    2021-02-03 12:43

    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 (1,'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.

提交回复
热议问题