1

当我执行以下查询时

select * from table where c2 = 11 or c3 = 15 or c7 = false

我得到这个结果

| c1 | c2 | c3 | c4  | c5  | c6      | c7     | c8        |
| 24 | 11 | 15 | NNN | NNN |         | true   | false     |
| 28 | 11 | 13 | NNN | NNN |         | true   | false     |
| 26 | 11 | 15 | NNN | NNN | wwwww   | false  | false     |
| 25 | 11 | 2  | NNN | NNN | qqqq    | false  | false     |
| 33 | 23 | 31 | NNN | NNN |         | false  | false     |
| 31 | 23 | 15 | NNN | NNN |         | false  | false     |
| 31 | 23 | 15 | NNN | NNN |         | true   | false     |
| 25 | 11 | 23 | NNN | NNN | qqqqw2  | false  | false     |
| 29 | 11 | 22 | NNN | NNN |         | true   | false     |

我试图通过搜索巧合来订购它,如下所示:

| c1 | c2 | c3 | c4  | c5  | c6      | c7    | c8        |
| 26 |[11]|[15]| NNN | NNN | wwwww   |[false]| false     |
| 24 |[11]|[15]| NNN | NNN |         | true  | false     |
| 25 |[11]| 2  | NNN | NNN | qqqq    |[false]| false     |
| 31 | 23 |[15]| NNN | NNN |         |[false]| false     |
| 25 |[11]| 23 | NNN | NNN | qqqqw2  |[false]| false     |
| 28 |[11]| 13 | NNN | NNN |         | true  | false     |
| 29 |[11]| 22 | NNN | NNN |         | true  | false     |
| 31 | 23 |[15]| NNN | NNN |         | true  | false     |
| 33 | 23 | 31 | NNN | NNN |         |[false]| false     |

因此,具有 3 个选项的行将位于顶部,然后是与至少 2 个选项匹配的所有行(无特定顺序),最后是与 1 个选项匹配的所有行,

有没有办法实现这个订单?因为我拥有的另一个选项是使用 and 语句组合选项,然后将 union 与所有结果一起使用,但似乎更多

提前致谢

4

2 回答 2

1

您需要添加一个 order by 子句:

order by (case when c2 = 11 then 1 else 0 end) +
         (case when c3 = 15 then 1 else 0 end) +
         (case when c7 = false then 1 else 0 end) desc

SQL 小提琴示例

于 2013-01-29T20:35:43.277 回答
1
order by
    (c2 = 11)::integer + (c3 = 15)::integer + (not c7)::integer desc

窃取@Gordon 的示例

于 2013-01-29T21:28:31.323 回答