Home > Database > Mysql Tutorial > How can I prioritize specific rows when ordering MySQL results?

How can I prioritize specific rows when ordering MySQL results?

Linda Hamilton
Release: 2025-01-14 07:06:46
Original
748 people have browsed it

How can I prioritize specific rows when ordering MySQL results?

MySQL result sorting and priority setting

This article describes how to prioritize specific rows in MySQL result sorting.

Method 1: Complete sorting

If you need to sort based on all possible values ​​in a field, regardless of their order:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core", "board", "other")
Copy after login

Method 2: Prioritize "core", the order of other values ​​does not matter

If you need to prioritize "core" and ignore the order of other values:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC
Copy after login

Method 3: Prioritize "core", then sort in regular order

If you need to prioritize "core", then sort in the usual order of the other values ​​in the field:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC, priority
Copy after login

Note:

  • This method may only work with MySQL.
  • FIELD() function returns the 1-based index of the value. If the value is not in the provided list, it will return zero, so DESC is usually required.

The above is the detailed content of How can I prioritize specific rows when ordering MySQL results?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template