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
Linda HamiltonOriginal
2025-01-14 07:06:46694browse

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:

<code class="language-sql">SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core", "board", "other")</code>

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:

<code class="language-sql">SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC</code>

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:

<code class="language-sql">SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC, priority</code>

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:
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