how to make sure a record is always at the top in a given resultset in mysql?

微笑、不失礼 提交于 2019-12-05 04:37:17
ORDER BY (p.id=14) DESC, (p.mPrice=p.vPrice) DESC

p.id=14 returns 1 if the condition is true, 0 otherwise, so sorting descending brings the desired row to the top.

Returning a number from a comparison is a MySQL feature, with standard SQL you would write:

ORDER BY CASE WHEN (p.id=14) THEN 0 ELSE 1 END,
         CASE WHEN (p.mPrice=p.vPrice) THEN 0 ELSE 1 END

I find this easier to read than the UNION, and it might perform better.

Use a union to always have your package at top:

SELECT id, name, mPrice, vPrice FROM package WHERE id = 14
UNION
SELECT p.id, p.name, p.mPrice, p.vPrice FROM package p 
WHERE p.name = LOWER('Thailand') or p.id = 14
ORDER BY (p.mPrice = p.vPrice) DESC
LIMIT 9

try this:

order by 
 case when p.id=14 then then (select MAX(mPrice)+1 from package ) else
(p.mPrice = p.vPrice)  end desc
LIMIT 10

Instead of (select MAX(p.mPrice)+1 from package ) you can give a constant value which would be always a maximun value, something like this

 order by 
 case when p.id=14 then then 1000000 else
(p.mPrice = p.vPrice)  end desc
LIMIT 10

which would be more effitient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!