Home > Database > Mysql Tutorial > How to Sort Rows Based on a Conditional Timestamp in MySQL?

How to Sort Rows Based on a Conditional Timestamp in MySQL?

Linda Hamilton
Release: 2024-11-13 04:46:01
Original
448 people have browsed it

How to Sort Rows Based on a Conditional Timestamp in MySQL?

MySQL ORDER BY CASE Sorting Issue

In MySQL, the ORDER BY clause allows you to sort query results based on specified columns. However, you may encounter difficulties when sorting multiple columns that depend on a specific condition.

Consider the following scenario:

You have a table with two columns, timestamp_one and timestamp_two. You need to retrieve all rows where either id_one or id_two is equal to 27. Additionally, you want to sort the results based on either timestamp_one or timestamp_two depending on whether id_one or id_two is 27.

While the following query correctly retrieves the required rows:

SELECT * FROM tablename 
WHERE id_one=27 OR id_two=27 
ORDER BY 
  CASE WHEN id_one=27 THEN timestamp_one END DESC, 
  CASE WHEN id_two=27 THEN timestamp_two END DESC
Copy after login

It sorts the rows by each column individually, rather than combining them into a single timestamp for sorting.

To resolve this issue, you can use the following modified query:

SELECT id_one, id_two, timestamp_one, timestamp_two      
FROM tablename 
WHERE id_one = 27 
    OR id_two = 27 
ORDER BY 
    CASE 
        WHEN id_one=27 THEN timestamp_one 
        WHEN id_two=27 THEN timestamp_two 
    END DESC 
Copy after login

In this modified query, we simplify the ORDER BY clause by using a single CASE expression to determine the sorting order. This allows us to sort the rows based on a combined timestamp that dynamically selects the appropriate column (timestamp_one or timestamp_two) depending on the value of id_one and id_two.

The above is the detailed content of How to Sort Rows Based on a Conditional Timestamp in MySQL?. 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