问题描述
我有一个 events 表,该表的 state 列。如果一切按计划进行,则状态只能是以下之一:
- 已计划
- 已邀请
- 已通知
- 已开始
- 已结束
是否可以通过状态进行订购并指定哪个值先出现,第二,第三等...?
奖励积分:在Rails 3中可以轻松做到这一点吗?
1。如果您只需要在postgres中使用一个sql,则为:
从事件
中选择*(计划时为案例状态
,通知时为1
,当被邀请,然后开始时为3
,然后为结束时为4
,然后为5
结束)
您可以更改sql中的状态顺序,无需更改ruby代码,播放sql小提琴:。。 p。
2。在mu的建议下,您可以使用枚举类型,它更有效,如果需要更改顺序,则可以重新创建枚举。看到以下sql小提琴: http://sqlfiddle.com/#!12/f6f3d/2
创建类型表示为枚举(邀请,预定,已通知,开始,结束 );
创建表事件(
名称为varchar(100),
状态为
);
从州中按事件顺序选择*;
3。以纯红宝石方式,您可以定义哈希:
test_hash = {'scheduled'=> 1,'notified'=> 2,'invited'=> 3,'started'=> 4 ,'ended'=> 5}
Events.all.sort! {| x,y | test_hash [x.state]< => test_hash [y.state]}
4。但在我看来,您应该添加一个名为状态和名称和序列列,并以序列指定顺序。然后加入事件和状态。更改订单时,无需更改代码。
I have an events table with a state column. If everything goes according to plan, the states can only be one of:
- scheduled
- invited
- notified
- started
- ended
Is it possible to order by state and specify which value comes first, second, third, etc...?
Bonus Points: Is there a way to do this easily in Rails 3?
1.If you just need a sql in postgres, here it is :
select * from events order by (case state when 'scheduled' then 1 when 'notified' then 2 when 'invited' then 3 when 'started' then 4 when 'ended' then 5 end)
you can change the order of states in sql, no need to change the ruby code, play the sql fiddle: http://sqlfiddle.com/#!12/976e9/3.
2.In mu's suggestion, you can use a enum type, it's more efficient, if you need to change the order, you can recreate the enum. see this sql fiddle: http://sqlfiddle.com/#!12/f6f3d/2
CREATE TYPE states AS ENUM ('invited', 'scheduled', 'notified', 'started', 'ended'); create table events( name varchar(100), state states ); select * from events order by state;
3.In pure ruby way, you can define a hash:
test_hash = {'scheduled'=>1, 'notified'=>2, 'invited'=>3, 'started'=>4, 'ended'=>5} Events.all.sort! {|x, y| test_hash[x.state] <=> test_hash[y.state]}
4.But in my opinion, you should add a table named "states", with columns "name" and "sequence", and specify the order in "sequence". Join the "events" and "states" then. When you change the order, you don't need to change the code.
这篇关于Postgres:按已知值的字符串列排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!