Home >Database >Mysql Tutorial >How Can I Efficiently Store and Retrieve Arrays of Data in MySQL Using Multiple Tables?
Storing Arrays in MySQL: A Multi-Table Solution
In MySQL, storing arrays directly is not straightforward due to the absence of an array data type. To store arrays of strings that reference values from another table, a multi-table design approach is commonly used.
Table Design
Create two tables: Person and Fruit. Person contains the name and an fruits column that will store array data. Fruit contains the fruit_name, color, and price.
CREATE TABLE Person ( `id` INT NOT NULL PRIMARY KEY, `name` VARCHAR(50), `fruits` VARCHAR(255) ); CREATE TABLE Fruit ( `fruit_name` VARCHAR(20) NOT NULL PRIMARY KEY, `color` VARCHAR(20), `price` INT );
Storing Array Data
To store an array of fruit names in the fruits column, you can use a comma-separated list. For example:
INSERT INTO Person (`name`, `fruits`) VALUES ('John Doe', 'apple,banana,orange');
Retrieving Array Data
To retrieve the array of fruit names for a person, use a JOIN query to link the Person and Fruit tables based on the fruit_name values.
SELECT p.name, f.fruit_name FROM Person p INNER JOIN Person_Fruit pf ON pf.person_id = p.id INNER JOIN Fruit f ON f.fruit_name = pf.fruit_name;
This query will return the name of the person and the fruit names associated with them.
The above is the detailed content of How Can I Efficiently Store and Retrieve Arrays of Data in MySQL Using Multiple Tables?. For more information, please follow other related articles on the PHP Chinese website!