按日期排序时出现语法错误

时间:2021-06-14 15:28:37

I'm using postgresql for a database on a Rails app that keeps track of when certain events take place. The database column for when the event takes place is called when (bad name, I know). I can do this

我正在使用postgresql为Rails应用程序上的数据库,该应用程序跟踪某些事件发生的时间。事件发生时的数据库列在(名字坏名字,我知道)时被调用。我可以做这个

@events = @group.events.order('created_at DESC')

However, when I do this

但是,当我这样做

 @events = @group.events.order('when DESC')

I get this error

我收到这个错误

PG::SyntaxError: ERROR:  syntax error at or near "when"
LINE 1: ..."events"  WHERE "events"."group_id" = $1  ORDER BY when DESC
                                                              ^
: SELECT "events".* FROM "events"  WHERE "events"."group_id" = $1  ORDER BY when DESC

A when record has this format in the database

当记录在数据库中具有此格式时

when: "2013-08-07"

Based on what I've told you, can you see the reason why I can't do this

根据我告诉你的内容,你能看出我不能这样做的原因

@events = @group.events.order('when DESC')

It's important for me to be able to order the events by when they are being held. Since ordering by created_at works, I don't see why the syntax error arises when I substitute a different column.

能够在举办活动时订购活动对我来说非常重要。由于created_at的排序有效,我不明白为什么当我替换不同的列时会出现语法错误。

1 个解决方案

#1


3  

  • WHEN is a reserved word in SQL (think about the Switch cases: CASE <smth> WHEN ...)

    WHEN是SQL中的保留字(想想Switch案例:CASE WHEN ......)

  • You can try accessing it like this:

    您可以尝试这样访问它:

    Event.order('events.when DESC')
    
  • You should change your column's name to something different than when (Take a look at @PhilipHallstrom comment)

    您应该将列的名称更改为与何时不同的内容(请查看@PhilipHallstrom注释)

#1


3  

  • WHEN is a reserved word in SQL (think about the Switch cases: CASE <smth> WHEN ...)

    WHEN是SQL中的保留字(想想Switch案例:CASE WHEN ......)

  • You can try accessing it like this:

    您可以尝试这样访问它:

    Event.order('events.when DESC')
    
  • You should change your column's name to something different than when (Take a look at @PhilipHallstrom comment)

    您应该将列的名称更改为与何时不同的内容(请查看@PhilipHallstrom注释)