Order by a value of an arbitrary attribute in hstore

自古美人都是妖i 提交于 2020-01-04 04:47:17

问题


I have records like these:

id, hstore_col
1,  {a: 1, b: 2}
2,  {c: 3, d: 4}
3,  {e: 1, f: 5}

How to order them by a maximum/minimum value inside hstore for any attribute?

The result should be like this(order by lowest):

id, hstore_col
1,  {a: 1, b: 2}
3,  {e: 1, f: 5}
2,  {c: 3, d: 4}

I know, I can only order them by specific attribute like this: my_table.hstore_fields -> 'a', but it doesn't work for my issue.


回答1:


Convert to an array using avals and cast the resulting array from text to ints. Then sort the array and order the results by the 1st element of the sorted array.

select * from mytable
order by (sort(avals(attributes)::int[]))[1]

http://sqlfiddle.com/#!15/84f31/5




回答2:


If you know all of the elements, you can just piece them all together like this:

ORDER BY greatest(my_table.hstore_fields -> 'a', my_table.hstore_fields -> 'b',my_table.hstore_fields -> 'c', my_table.hstore_fields -> 'd', my_table.hstore_fields -> 'e', my_table.hstore_fields -> 'f')

or

ORDER BY least(my_table.hstore_fields -> 'a', my_table.hstore_fields -> 'b',my_table.hstore_fields -> 'c', my_table.hstore_fields -> 'd', my_table.hstore_fields -> 'e', my_table.hstore_fields -> 'f')



回答3:


By using svals you can create an exploded version of the hstore_col's values - then you can sort on those values and get the first entry from each of them. There is doubtlessly a much more efficient way to do this, but here's a first pass:

select my_table.id, my_table.hstore_col
from my_table
join (
    select id, svals(hstore_col) as hstore_val
    from my_table
) exploded_table
    on my_table.id = exploded_table.id
group by my_table.id, my_table.hstore_col
order by my_table.id, exploded_table.hstore_val desc


来源:https://stackoverflow.com/questions/26591244/order-by-a-value-of-an-arbitrary-attribute-in-hstore

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