ORDER子句与表达式
问题描述:
我有以下查询。ORDER子句与表达式
SELECT
mp.id
FROM
p_maint_prior pmp
JOIN maint_prior mp ON(pmp.cid=mp.cid AND pmp.main_pr_id = mp.id)
WHERE
pmp.property_id = 12345
AND pmp.cid = 235
AND pmp.remote_primary_key IS NOT NULL
ORDER BY
mp.maint_prio_type_id = 3,
mp.maint_prio_type_id DESC
LIMIT 1;
有了这个查询,它给了我优先,如果它有类型ID 3,否则它会给随机的。想了解更多关于ORDER BY子句中使用的表达式的信息。
答
关闭。这ORDER BY
提出3 最后不第一:
ORDER BY mp.maint_prio_type_id = 3, mp.maint_prio_type_id DESC
原因很简单: “真” 比 “假” 做大。这是更容易理解,如果你这样做:
ORDER BY (mp.maint_prio_type_id = 3)::int, mp.maint_prio_type_id DESC
这给“真”的值为“1”和假的值为“0”。排序顺序显而易见。
如果你想“3”第一,然后把DESC旁边的第一个关键:
ORDER BY (mp.maint_prio_type_id = 3) DESC, mp.maint_prio_type_id DESC
这是一个奇怪的概念,但是 - 与在SQL很多东西 - 一个被用来它很快。
你能更具体吗?什么是问题? –