ホームページ  >  記事  >  データベース  >  CASE ステートメントを使用して MySQL の複数のタイムスタンプ列に基づいて行を並べ替える方法

CASE ステートメントを使用して MySQL の複数のタイムスタンプ列に基づいて行を並べ替える方法

Susan Sarandon
Susan Sarandonオリジナル
2024-11-15 09:59:02575ブラウズ

How to Order Rows Based on Multiple Timestamp Columns in MySQL with CASE Statement?

MYSQL ORDER BY CASE Issue

This question poses a challenge in ordering rows based on specific columns depending on a WHERE condition. Consider the provided database with four rows and timestamp columns. The goal is to order the rows such that both timestamp columns are treated as a single ordering criterion.

The query provided initially sorts the timestamps based on the id_one and id_two fields separately:

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

This approach results in an output where the rows are sorted within each id_one or id_two group, but not as a combined timestamp ordering.

To achieve the desired ordering, we can use a slightly 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 

In this revised query, both timestamp_one and timestamp_two are considered for ordering, regardless of which ID column matches the WHERE condition. The CASE statement selects the appropriate timestamp based on the id_one and id_two values.

This modification results in the desired output, where the rows are ordered as a single timestamp column, taking both timestamp_one and timestamp_two into account:


| id_one | id_two | timestamp_one | timestamp_two |

| 27 | 35 | 9:30 | NULL |

| 35 | 27 | NULL | 9:33 |

| 27 | 35 | 9:34 | NULL |

| 35 | 27 | NULL | 9:35 |

以上がCASE ステートメントを使用して MySQL の複数のタイムスタンプ列に基づいて行を並べ替える方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。