我有一个类似SELECT * FROM my_table WHERE column_a = 'foo' OR column_b = 'foo' ORDER BY column_c;
的查询。
是否有办法在结果中首先获得与第一个条件column_a = 'foo'
匹配的行(由column_c
值排序),然后匹配第二个条件column_b = 'foo'
的行(按顺序排列) column_c
值)?
答案 0 :(得分:2)
您可以通过布尔表达式对行进行排序,例如:
SELECT *
FROM my_table
WHERE column_a = 'foo' OR column_b = 'foo'
ORDER BY column_a <> 'foo', column_b <> 'foo', column_c;
答案 1 :(得分:2)
SELECT *
FROM my_table
WHERE column_a = 'foo' OR column_b = 'foo'
ORDER BY CASE WHEN column_a = 'foo' then 1 ELSE 2 END, column_c
同样,如果你有另一个OR
条件:
SELECT *
FROM my_table
WHERE column_a = 'foo' OR column_b = 'foo' OR column_c = 'foo'
ORDER BY CASE WHEN column_a = 'foo' then 1 WHEN column_b = 'foo' then 2 ELSE 3 END, column_d
答案 2 :(得分:0)
您可以添加order by column_a, column_b, column_c
,这将订购行