Home > Database > Mysql Tutorial > How Can I Efficiently Store and Retrieve Arrays of Data in MySQL Using Multiple Tables?

How Can I Efficiently Store and Retrieve Arrays of Data in MySQL Using Multiple Tables?

Susan Sarandon
Release: 2024-12-05 19:54:11
Original
465 people have browsed it

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
);
Copy after login

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');
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template