Table of Contents
1. Store arrays in the form of strings in MySQL
2.MySQL中存储数组(list)的示例
说明一:
说明二:
Home Database Mysql Tutorial Does mysql have arrays?

Does mysql have arrays?

Mar 30, 2023 pm 08:15 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. Relational databases 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, 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.

Does mysql have arrays?

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

1. Store arrays in the form of strings in MySQL

There are no array types in MySQL. Array elements are usually divided by a certain character and stored in the form of strings

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 method is very simple, just look at how many delimiters exist in the string, and then add one to get the required result.

CREATE function Get_StrArrayLength 
( 
@str varchar(1024), --要分割的字符串 
@split varchar(10) --分隔符号 
) 
returns int 
as 
begin 
declare @location int 
declare @start int 
declare @length int 
set @str=ltrim(rtrim(@str)) 
set @location=charindex(@split,@str) 
set @length=1 
while @location<>0 
begin 
set @start=@location+1 
set @location=charindex(@split,@str,@start) 
set @length=@length+1 
end 
return @length 
end
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

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

Calling 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

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

调用结果:

1
2
3
4
5
Copy after login

2.MySQL中存储数组(list)的示例

我在MySQL中有两个表。表Person具有以下列:

id | name | fruits
Copy after login

水果列可以包含空或像(‘apple’,’orange’,’banana’)或(‘strawberry’)等的字符串数组。第二个表是Table Fruit,有以下三列:

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

那么我应该如何设计第一个表中的fruits列,以便它可以容纳从第二个表中的fruit_name列获取值的字符串数组?由于MySQL中没有数组数据类型,我该怎么办呢?

最佳答案:

正确的方法是使用多个表,并在查询中加入它们。

例如:

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_fruit表包含一个人与其相关联的每个水果的一行,并且有效地将人和水果表链接在一起。

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

当你想检索一个人和他们的水果,你可以做这样的事情:

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

说明一:

SQL中没有数组的原因是因为大多数人并不真正需要它。关系数据库(SQL就是这样)使用关系工作,并且大多数情况下,最好是为每个“信息位”分配一行表。例如,你可能认为“我想要一个东西列表”,而是创建一个新表,将一个表中的行与另一个表中的行相关联[1] 这样,您可以表示M:N关系。另一个优点是这些链接不会使包含链接项的行混乱。数据库可以索引这些行。数组通常不会编入索引。

如果您不需要关系数据库,则可以使用例如键值存储。

黄金法则是“[每个]非关键[属性]必须提供关于密钥,整个密钥以及密钥的事实。” 数组做得太多了。它有多个事实,它存储订单(与关系本身无关)。性能很差(见上文)。

想象一下,你有一张人桌,你有一张桌子,可以让人打电话。现在你可以让每个人都有他的电话列表。但每个人与许多其他事物有许多其他关系。这是否意味着我的人员表应该包含他连接的每一件事物的数组?不,这不是这个人本身的属性。

[1]:如果链接表只有两列(每个表的主键),这没关系!如果关系本身具有其他属性,则应在此表中将其表示为列。

说明二:

MySQL 5.7现在提供JSON数据类型。这种新的数据类型提供了一种存储复杂数据的便捷新方法:列表,字典等。

也就是说,rrays不能很好地映射数据库,这就是对象关系映射可能非常复杂的原因。历史上,人们通过创建描述它们的表并将每个值添加为自己的记录来在MySQL中存储列表/数组。该表可能只有2或3列,或者可能包含更多列。如何存储此类数据实际上取决于数据的特征。

例如,列表是否包含静态或动态条目数?该列表是否会保持较小,或者预计会增长到数百万条记录?这张桌子上会有很多读物吗?很多写作?很多更新?在决定如何存储数据集合时,这些都是需要考虑的因素。

此外,密钥:价值数据存储/文件存储,如Cassandra,MongoDB,Redis等也提供了一个很好的解决方案。请注意数据实际存储的位置(如果存储在磁盘或内存中)。并非所有数据都需要位于同一数据库中。某些数据无法很好地映射到关系数据库,您可能有理由将其存储在其他位置,或者您可能希望使用内存中的键:值数据库作为存储在磁盘某处或作为临时存储的数据的热缓存像会话这样的东西。

【相关推荐:mysql视频教程

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles