[英]Ordering by Member of Composite Type Postgres
取下表:
CREATE TABLE test(id serial primary key, txt text);
INSERT INTO test (id,txt) values (1,'one'),(2,'two'),(3,'three')
和自定义类型:
CREATE TYPE tttpe AS (id integer, name varchar(32), greee integer);
我正在转换这样的查询:
SELECT id, txt, (id+10) as gree FROM test ORDER BY 2
其中2是动态的,类似于这样的查询:
SELECT (id, txt, (id+10))::tttpe FROM test; --order by!?
但我想按自定义类型的成员(例如txt.
进行排序txt.
我该怎么做呢? 理想情况下,我希望能够为nth属性使用整数索引,但是如果不可能,我可以解决它。
更新:
根据Clodoaldo Neto的回答,我得出以下结论:
SELECT (id,txt,g)::tttpe FROM (select id, txt, (id+10) FROM test ORDER BY 2) AS s;
尽管实际上我有40多个字段,所以不得不两次列出它们是一件很痛苦的事情。
select (tt).id, (tt).name, (tt).greee, tt
from (
select (id, txt, id+10)::tttpe as tt
from test
) s
order by 3 desc
没有子选择
select
((id, txt, id+10)::tttpe).id,
((id, txt, id+10)::tttpe).name,
((id, txt, id+10)::tttpe).greee,
(id, txt, id+10)::tttpe as tt
from test
order by 3 desc
由于评论中非常重要的上下文更改而进行编辑
在函数或子选择内部完成的排序不能保证是其输出之一,因此请勿在函数内部进行排序。 但好消息是,从函数访问类型的每个成员要容易得多
create or replace function get_tt()
returns tttpe as $$
select (id, txt, id+10)::tttpe as tt
from test;
$$ language sql;
select id, name, greee
from get_tt()
order by 3 desc;
但是,如果您想要原始对象,如下面的查询中所示,那么您将回到第一平方
select get_tt();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.