[Project Combat] MySQL uses the FIELD() function and the ORDER BY clause to implement. When sorting, remove a field without sorting

1. SQL Requirements Description

Suppose there is a table named table_name, which contains id, name and version fields, and
the business side wants to sort in ascending order according to the name field, but does not want to sort by the version field

2. Function realization

You can use MySQL's FIELD() function and ORDER BY clause to implement a sorting operation that removes a field without sorting.
The following SQL statement:

SELECT *
FROM table_name 
ORDER BY FIELD(version, 'latest') DESC, name ASC;

Compare the version field with the string 'latest' by using the FIELD(version, 'latest') function,
and return 0 if the version field is equal to 'latest', and 1 otherwise.
In this way, when the version field is equal to 'latest', it will be ranked last, achieving the effect of removing a certain field without sorting.

Then we use the ORDER BY clause to sort in ascending order according to the name field (ASC means ascending order, DESC means descending order).

Note: When using the FIELD() function, you need to ensure that the string 'latest' and all version values ​​in the table are case-insensitive, otherwise the comparison result may be incorrect.

Other statements are as follows

order by FIELD(version,'latest') desc, deploy_time desc
SELECT * FROM table_name ORDER BY field_name ASC, field_to_exclude ASC
SELECT * FROM table_name ORDER BY FIELD(field_name) ASC, field_to_exclude ASC

3. Introduction to FIELD() function

3.1 What is the FIELD() function?

MySQL's FIELD() function is a string function used to return the position of a field among multiple values.

3.2 Syntax of the FIELD() function

Its syntax is as follows:

FIELD(column, value1, value2, value3, ...)

Among them, column is the field name of the location to be searched, and value1, value2, value3, etc. are the values ​​to be compared.

The result of the FIELD() function is,

  • When column matches value1, return 1;
  • When column matches value2, return 2;
  • When column matches value3, return 3, and so on.
  • Returns NULL if column does not match any values.

3.3 Usage scenario of FIELD() function

This function is typically used in an ORDER BY clause to sort by the position of a particular value among multiple values.

For example, the following query will sort in descending order by the position of the version field among multiple values:

SELECT * FROM table_name ORDER BY FIELD(version, '1.0', '2.0', '3.0') DESC;

This will sort first by the position of the version field in '1.0', '2.0', '3.0', then sort in descending lexicographical order.

Guess you like

Origin blog.csdn.net/wstever/article/details/129562217