Table of Contents
1. MySQL stores arrays in the form of strings
2. Example of storing array (list) in MySQL
Instruction one:
MySQL 5.7 now provides the JSON data type. This new data type provides a storage Convenient new methods for complex data: lists, dictionaries, etc. Object-relational mapping can be very complex because Rrays cannot be efficiently mapped to databases. In MySQL, historically people usually created tables to store lists or arrays , and add each value as a record. The table may only have 2 or 3 columns, or it may contain more. How you store this type of data really depends on the characteristics of the data.
Home Database Mysql Tutorial Does mysql have arrays?

Does mysql have arrays?

Jun 03, 2023 pm 12:04 PM
mysql

There are no array types in MySQL. Array elements are usually divided by a certain character and stored in string form. The reason there are no arrays in MYSQL is because most people don't really need it. In relational databases, typically using a relational model, each unit of information is best assigned to a separate table row. For example, one might think "I want a list of things" and instead create a new table that relates rows from one table to rows from another table; this can represent an "M:N" relationship. The database can index these rows; arrays typically are not indexed.

1. MySQL stores arrays in the form of strings

There are no array types in MySQL. Array elements are usually divided into strings by a certain character. Format storage

1.1. Find the number of elements in the array

Method: Split the string according to the specified symbol and return the number of elements after splitting. The required result can be obtained by counting the number of delimiters in the string and adding 1. The method is very simple.

<code>CREATE function Get_StrArrayLength <br/>( <br/>@str varchar(1024), --要分割的字符串 <br/>@split varchar(10) --分隔符号 <br/>) <br/>returns int <br/>as <br/>begin <br/>declare @location int <br/>declare @start int <br/>declare @length int <br/>set @str=ltrim(rtrim(@str)) <br/>set @location=charindex(@split,@str) <br/>set @length=1 <br/>while @location<>0 <br/>begin <br/>set @start=@location+1 <br/>set @location=charindex(@split,@str,@start) <br/>set @length=@length+1 <br/>end <br/>return @length <br/>end<br/></code>
Copy after login

Calling example:

select  Get_StrArrayLength(&#39;78,1,2,3&#39;,&#39;,&#39;)
Copy after login

Return value:

4
Copy after login

1.2. Get the element at the specified position in the array

Method: Split the string according to the specified symbol and return the element of the specified index after splitting (note that the index starts from 1), as convenient as an array

<code>CREATE function Get_StrArrayStrOfIndex <br/>( <br/>@str varchar(1024), --要分割的字符串 <br/>@split varchar(10), --分隔符号 <br/>@index int --取第几个元素 <br/>) <br/>returns varchar(1024) <br/>as <br/>begin <br/>declare @location int <br/>declare @start int <br/>declare @next int <br/>declare @seed int <br/>set @str=ltrim(rtrim(@str)) <br/>set @start=1 <br/>set @next=1 <br/>set @seed=len(@split) <br/>set @location=charindex(@split,@str) <br/>while @location<>0 and @index>@next <br/>begin <br/>set @start=@location+@seed <br/>set @location=charindex(@split,@str,@start) <br/>set @next=@next+1 <br/>end <br/>if @location =0 select @location =len(@str)+1 <br/>--这儿存在两种情况:1、字符串不存在分隔符号 2、字符串中存在分隔符号,跳出while循环后,@location为0,那默认为字符串后边有一个分隔符号。 <br/>return substring(@str,@start,@location-@start) <br/>end<br/></code>
Copy after login

Call example:

select  Get_StrArrayStrOfIndex(&#39;8,9,4&#39;,&#39;,&#39;,2)
Copy after login

Return value:

9
Copy after login

1.3. Combine the above two functions to traverse the elements in the array

Method: Combine the above two functions to traverse the elements in the string like an array

<code>declare @str varchar(50) <br/>set @str=&#39;1,2,3,4,5&#39; <br/>declare @next int <br/>set @next=1 <br/>while @next<=Get_StrArrayLength(@str,&#39;,&#39;) <br/>begin <br/>print Get_StrArrayStrOfIndex(@str,&#39;,&#39;,@next) <br/>set @next=@next+1 <br/>end<br/></code>
Copy after login

Call result:

1
2
3
4
5
Copy after login

2. Example of storing array (list) in MySQL

I have two tables in MySQL. Table Person has the following columns:

id | name | fruits
Copy after login

The fruit column can contain empty or an array of strings like (‘apple’, ‘orange’, ‘banana’) or (‘strawberry’) etc. The second table is Table Fruit, with the following three columns:

____________________________
fruit_name | color  | price
____________________________
apple      | red    | 2
____________________________
orange     | orange | 3
____________________________
...,...
Copy after login

So how should I design the fruits column in the first table so that it can accommodate getting the value from the fruit_name column in the second table String array? Since there is no array data type in MySQL, what should I do?

Best answer:

The correct way is to use multiple tables and join them in the query.

For example:

CREATE TABLE person (
`id` INT NOT NULL PRIMARY KEY,
`name` VARCHAR(50)
);
 
CREATE TABLE fruits (
`fruit_name` VARCHAR(20) NOT NULL PRIMARY KEY,
`color` VARCHAR(20),
`price` INT
);
 
CREATE TABLE person_fruit (
`person_id` INT NOT NULL,
`fruit_name` VARCHAR(20) NOT NULL,
PRIMARY KEY(`person_id`, `fruit_name`)
);
Copy after login

person_fruitThe table contains a row for each fruit that a person is associated with, and effectively links the people and fruits tables together.

1 | "banana"
1 | "apple"
1 | "orange"
2 | "straberry"
2 | "banana"
2 | "apple"
Copy after login

When you want to retrieve a person and their fruit, you can do something like this:

SELECT p.*, f.*
FROM person p
INNER JOIN person_fruit pf
ON p.id = pf.person_id
INNER JOIN fruits f
ON pf.fruit_name = f.fruit_name
Copy after login

Instruction one:

The reason there are no arrays in SQL is because most people don't really need it. Relational databases (that's what SQL is) work using relationships, and most of the time it's best to have one row of the table for each "bit of information". For example, you might think "I want a list of things ", instead create A new table that relates rows in one table to rows in another table. [1] In this way, you can represent M:N relationships. Another advantage is that these links do not clutter the row containing the linked item. The database can index these rows. Arrays are generally not indexed. If you don't need a relational database, you can use e.g. a key-value store. "Information. Rewritten sentence: According to the golden rule, each non-key attribute must provide corresponding information for the key and the entire key fact. "The array does too much. It has multiple facts, it stores the order (not related to the relationship itself). The performance is poor (see above).

Imagine you have a table of people and you have A table where people can make phone calls. Now you can have each person have his phone list. But each person has many other relationships with many other things. Does this mean my people table should contain every thing he is connected to? Array of things? No, that's not a property of the person itself.

[1]: If the linked table only has two columns (the primary key of each table), that's okay! If the relationship itself has other properties, it should Represent it as a column in this table.

Note two:

MySQL 5.7 now provides the JSON data type. This new data type provides a storage Convenient new methods for complex data: lists, dictionaries, etc. Object-relational mapping can be very complex because Rrays cannot be efficiently mapped to databases. In MySQL, historically people usually created tables to store lists or arrays , and add each value as a record. The table may only have 2 or 3 columns, or it may contain more. How you store this type of data really depends on the characteristics of the data.

For example, does the list contain Static or dynamic number of entries? Will the list stay small, or is it expected to grow to millions of records? Will there be a lot of reading on this table? A lot of writing? A lot of updating? These are important considerations when deciding how to store your data collection These are all factors that need to be considered.

Additionally, key:value data stores/file stores such as Cassandra, MongoDB, Redis, etc. also provide a good solution. Note where the data is actually stored (if on disk or in memory). Not all data needs to be in the same database. Some data doesn't map well to a relational database and you may have reasons to store it elsewhere, or you may want to use an in-memory key:value database as a hot cache for data stored somewhere on disk or as temporary storage Things like sessions.

The above is the detailed content of Does mysql have arrays?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

See all articles