【问题标题】:Database query for array data type receives error: No operator matches the given name and argument type(s)数组数据类型的数据库查询收到错误:没有运算符与给定名称和参数类型匹配
【发布时间】:2017-01-26 16:29:30
【问题描述】:

我的网球日历模型将周属性设置为数组数据类型,因为锦标赛可以持续两周。例如,第一个元素如下:

2.3.1 :001 > AtpCalendar.first
  AtpCalendar Load (0.8ms)  SELECT  "atp_calendars".* FROM "atp_calendars" ORDER BY "atp_calendars"."id" ASC LIMIT $1  [["LIMIT", 1]]
 => #<AtpCalendar id: 1, name: "Brisbane", category: "ATP 250", week: [1], created_at: "2017-01-25 17:29:36", updated_at: "2017-01-25 17:29:36">

如果我向 Postgresql 查询星期属性的类型,我会得到预期的答案:

2.3.1 :001 > AtpCalendar.first.week == [1]
  AtpCalendar Load (0.8ms)  SELECT  "atp_calendars".* FROM "atp_calendars" ORDER BY "atp_calendars"."id" ASC LIMIT $1  [["LIMIT", 1]]
 => true
2.3.1 :001 > AtpCalendar.first.week.class
  AtpCalendar Load (0.9ms)  SELECT  "atp_calendars".* FROM "atp_calendars" ORDER BY "atp_calendars"."id" ASC LIMIT $1  [["LIMIT", 1]]
 => Array 

所以到目前为止没有问题。
但是,如果我在 Postgres 中查询特定周值,例如 [1],我会收到错误消息:

2.3.1 :002 > AtpCalendar.where('week = ?', [1])
  AtpCalendar Load (1.7ms)  SELECT "atp_calendars".* FROM "atp_calendars" WHERE (week = 1)
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: integer[] = integer
LINE 1: ...LECT "atp_calendars".* FROM "atp_calendars" WHERE (week = 1)
                                                                   ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

我也尝试了不同的查询,但结果是一样的:

2.3.1 :001 > AtpCalendar.where("week @> ?", 1)
  AtpCalendar Load (1.6ms)  SELECT "atp_calendars".* FROM "atp_calendars" WHERE (week @> 1)
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: integer[] @> integer
LINE 1: ...ECT "atp_calendars".* FROM "atp_calendars" WHERE (week @> 1)
                                                                  ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

我可能遗漏了一些东西,但我不明白是什么。
当我使用查询AtpCalendar.find_by(week: [1])时出现同样的错误

【问题讨论】:

    标签: ruby-on-rails postgresql rails-activerecord


    【解决方案1】:

    我假设它实际上是数据库中的一个字符串?

    AtpCalendar.where(week: '[1]')
    

    【讨论】:

    • 关闭。我发现 Postgres 使用大括号,而不是数组的方括号。所以最后正确的查询是 AtpCalendar.where(week: '{1}')
    猜你喜欢
    • 1970-01-01
    • 2013-01-20
    • 2016-07-07
    • 1970-01-01
    • 2014-09-05
    • 2021-05-11
    • 2021-02-18
    • 2013-08-20
    相关资源
    最近更新 更多