How to store a list in a db column

后端 未结 6 822
悲哀的现实
悲哀的现实 2020-11-30 19:25

I would like to store an object FOO in a database. Lets say FOO contains three integers and a list of \"Fruits\".

The list can have any len

6条回答
  •  失恋的感觉
    2020-11-30 20:07

    In a normalized relational database, such a situation is unacceptable. You should have a junction table that stores one row for each distinct ID of the FOO object and the ID of the Fruit. Existence of such a row means the fruit is in that list for the FOO.

    CREATE TABLE FOO ( 
      id int primary key not null,
      int1 int, 
      int2 int, 
      int3 int
    )
    
    CREATE TABLE Fruits (
      id int primary key not null,
      name varchar(30)
    )
    
    CREATE TABLE FOOFruits (
      FruitID int references Fruits (ID),
      FooID int references FOO(id),
      constraint pk_FooFruits primary key (FruitID, FooID)
    )
    

    To add Apple fruit to the list of a specific FOO object with ID=5, you would:

    INSERT FOOFruits(FooID, FruitID)
    SELECT 5, ID FROM Fruits WHERE name = 'Apple'
    

提交回复
热议问题