Does mysql have arrays?
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>
Calling example:
select Get_StrArrayLength('78,1,2,3',',')
Return value:
4
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>
Call example:
select Get_StrArrayStrOfIndex('8,9,4',',',2)
Return value:
9
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='1,2,3,4,5' <br/>declare @next int <br/>set @next=1 <br/>while @next<=Get_StrArrayLength(@str,',') <br/>begin <br/>print Get_StrArrayStrOfIndex(@str,',',@next) <br/>set @next=@next+1 <br/>end<br/></code>
Call result:
1 2 3 4 5
2. Example of storing array (list) in MySQL
I have two tables in MySQL. Table Person has the following columns:
id | name | fruits
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 ____________________________ ...,...
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`) );
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"
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.
