Home >Database >Mysql Tutorial >How Should I Store Lists of Related Data in a Relational Database?
Storing hierarchical data, such as lists, in a database column can be a challenge. Let's consider a scenario where you want to store an object FOO that contains a list of fruits, and where fruits are stored in a separate table.
In a normalized relational database, it is not recommended to store a list directly in a column. This creates data integrity issues and makes it difficult to maintain and query the data effectively. Instead, you should create a junction table that relates the FOO object to the fruits.
Designing the Database Schema
Create the following tables:
Example Schema:
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) );
Populating the Data
To add a fruit to the list of a FOO object, insert a row into the FOOFruits table:
INSERT FOOFruits(FooID, FruitID) SELECT 5, ID FROM Fruits WHERE name = 'Apple';
Advantages of Normalized Design
The above is the detailed content of How Should I Store Lists of Related Data in a Relational Database?. For more information, please follow other related articles on the PHP Chinese website!