开发者

HQL sorting records by using greatest of 2 columns

开发者 https://www.devze.com 2023-04-06 04:00 出处:网络
For each row in my database开发者_如何学Go, I have 2 columns, say id and A. Sometimes A can benull. I want to sort all records by greatest of its id and A value, but if A is null, it will be ignored a

For each row in my database开发者_如何学Go, I have 2 columns, say id and A. Sometimes A can be null. I want to sort all records by greatest of its id and A value, but if A is null, it will be ignored and the column will be sorted by id instead.

I'm using Hibernate and database as MySQL. So far, my HQL is like

select i from Item as i order by GREATEST(id, a)

it is working fine except for the records with A=null. For those values, they appear at the end of the returning results (they're supposed to be sorted using their id as key).

How to write such an HQL statement?


Somebody solved it with Case..When..End, works perfectly.

select i from Item as i order by CASE WHEN a = null THEN id ELSE GREATEST(id, a) END DESC
0

精彩评论

暂无评论...
验证码 换一张
取 消