Query

在同一列上使用兩個標識符選擇兩行時確保順序

  • November 1, 2018

我正在嘗試編寫一個查詢,以使用同一列從表中準確檢索兩行以進行辨識。

SELECT * FROM teams WHERE name = $1 OR name = $2;

有什麼方法可以確保name = $1返回的結果是第一個結果name = $2是第二個?

SELECT * 
FROM teams 
WHERE name IN ($1, $2)
ORDER BY CASE WHEN name = $1 THEN 0 ELSE 1 END;

另一種方法是將參數及其各自的排序值排列為(派生)表,連接該表並使用 ORDER BY 中的排序列:

SELECT
 t.*
FROM
 teams AS t
 INNER JOIN
   (
     SELECT $1 AS name, 1 AS sort
     UNION ALL
     SELECT $2 AS name, 2 AS sort
   ) AS s ON t.name = s.name
ORDER BY
 s.sort ASC
;

引用自:https://dba.stackexchange.com/questions/103245