Home > Database > Mysql Tutorial > How to Order Rows Based on the Order in a WHERE IN Clause?

How to Order Rows Based on the Order in a WHERE IN Clause?

DDD
Release: 2024-10-27 12:40:03
Original
425 people have browsed it

How to Order Rows Based on the Order in a WHERE IN Clause?

Order Rows According to WHERE IN Clause Using ORDER BY FIELD

In database queries, the WHERE IN clause allows you to filter data based on a specified list of values. However, by default, the rows returned may not be in the same order as specified in the clause.

To order the rows according to the order provided in the WHERE IN clause, you can use the ORDER BY FIELD() function. This function takes two arguments:

  • The field you want to sort the rows by (in this case, the id field)
  • A comma-separated list of values from the WHERE IN clause

For example, given the following query:

SELECT *
FROM table
WHERE id IN (118, 17, 113, 23, 72);
Copy after login

Which returns the rows in ascending order by ID, you can use the ORDER BY FIELD() function to get the rows in the order specified in the WHERE IN clause:

SELECT *
FROM table
WHERE id IN (118, 17, 113, 23, 72)
ORDER BY FIELD(id, 118, 17, 113, 23, 72)
Copy after login

In this query, the ORDER BY FIELD() function sorts the rows by the id field, but in the specific order of 118, 17, 113, 23, and 72, as specified in the WHERE IN clause.

Using this technique, you can easily order rows according to the order specified in your WHERE IN clause, ensuring that they are returned in the desired sequence.

The above is the detailed content of How to Order Rows Based on the Order in a WHERE IN Clause?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template