


Does php mysql select support explode fields and then sort according to values?
1. For example, the format of a field in the table is as follows: data 1|||||data 2|||||data 3
2. Now I want to split the data into $data[0],$data[1],$ data[3], and then order by $data[3]
3. Can this be achieved?
4. A complete novice, the description may not be standardized, but the meaning should be clear.
Reply content:
1. For example, the format of a field in the table is as follows: data 1|||||data 2|||||data 3
2. Now I want to split the data into $data[0],$data[1],$ data[3], and then order by $data[3]
3. Can this be achieved?
4. A complete novice, the description may not be standardized, but the meaning should be clear.
It can be implemented, but if implemented at the MySQL level, it may cause greater pressure on the database.
You can consider sorting it in the PHP program, and then fetching the data from MySQL based on the ID sequence.
<code><?php header('Content-Type: text/plain; charset=utf-8'); //$db = new mysqli('127.0.0.1','user','pass','dbname',3306); //$arr = $db->query('SELECT id,field FROM table')->fetch_all(MYSQLI_ASSOC); //假设取出来的数据结构如下 $arr = array( array('id' => 1, 'field' => '数据1|||||数据2|||||256'), array('id' => 2, 'field' => '数据1|||||数据2|||||128'), array('id' => 3, 'field' => '数据1|||||数据2|||||512'), ); foreach($arr as $k => $v) { //把field字段的内容转成一个数组比如array('数据1','数据2','256'),方便后面排序 $arr[$k]['field'] = explode('|||||', $v['field']); } //根据field字段里的第三个元素对数组进行排序 uasort($arr, function($a, $b) { if($a['field'][2]===$b['field'][2]) return 0; //下面这句话的意思就是,如果前面的a大过后面的b,就返回1,返回1表示交换顺序,也就是小的数在前面,由小到大升序排列. else return ($a['field'][2] > $b['field'][2]) ? 1 : -1; }); foreach($arr as $k => $v) { $ids[] = $v['id']; } $ids = implode(',', $ids); //ID序列为2,1,3 //按照ID序列的顺序查询MySQL //SQL语句为 SELECT * FROM table WHERE id IN(2,1,3) ORDER BY FIELD(id,2,1,3) $sql = "SELECT * FROM table WHERE id IN($ids) ORDER BY FIELD(id,$ids)"; //$ret = $db->query($sql)->fetch_all();</code>
If the amount of data is large, you can consider caching the ID sequence arranged by PHP.
ORDER BY FIELD (id, $ids) This operation will also cause performance problems when the amount of data is large.
At this time, you can consider caching the ID sequence based on the actual situation. Segment $ids, for example, sort 20 items from 0 to 19 on the first page, and so on on the second page. In this way, custom sorting of small data amounts will put much less pressure on MySQL.
This has nothing to do with php. You can create a function with mysql and then use the function to sort:
<code>CREATE FUNCTION SPLIT_STRING(str VARCHAR(255), delim VARCHAR(12), pos INT) RETURNS VARCHAR(255) RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos), LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1), delim, '');</code>
<code>SELECT * FROM test_table order by SPLIT_STRING(test_tablecol, '|||', 3);</code>
It can be implemented, but it is very troublesome and very inefficient. The usual solution to this requirement is to modify the table structure.
From a purely logical point of view, SQL can actually do very complex things, but do you think if a query takes several minutes to run and your family members find out, will you be beaten?
It is recommended to use php to sort after querying, not mysql
substring_index of mysql

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

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

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











MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Installing MySQL on macOS can be achieved through the following steps: 1. Install Homebrew, using the command /bin/bash-c"$(curl-fsSLhttps://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)". 2. Update Homebrew and use brewupdate. 3. Install MySQL and use brewinstallmysql. 4. Start MySQL service and use brewservicesstartmysql. After installation, you can use mysql-u
