Home > Database > Mysql Tutorial > body text

How Can I Preserve Row Order in Conditional Queries Using `WHERE IN` Clause?

Barbara Streisand
Release: 2024-10-27 02:39:03
Original
449 people have browsed it

How Can I Preserve Row Order in Conditional Queries Using `WHERE IN` Clause?

Preserving Row Order in Conditional Queries

Problem:

When using the WHERE IN clause, the rows are typically ordered ascendingly by the column specified in the ORDER BY clause. However, there are scenarios where it is desired to maintain the order of rows as specified in the IN clause.

Solution:

To achieve this, you can employ the ORDER BY FIELD function. This function reorders the rows based on the specified order in its arguments.

Example:

Consider the following query:

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

This query will return the rows ordered by id ascendingly. To preserve the order of rows as specified in the IN clause, you can use the following modified query:

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

By specifying the desired order as arguments to the FIELD function, the rows will be reordered to match that order.

The above is the detailed content of How Can I Preserve Row Order in Conditional Queries Using `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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!