【问题标题】:Converting rails query from Mysql to PostgreSQL将 Rails 查询从 Mysql 转换为 PostgreSQL
【发布时间】:2013-10-08 19:29:04
【问题描述】:

谁能告诉我如何将此查询转换为 PostgreSQL

routes_controller.rb

@routes = Route.joins([:departure_location, :destination_location]).where("mdm_locations.name like ? or destination_locations_mdm_routes.name like ?" , "%#{k}%", "%#{k}%")

routes.rb(模型)

module Mdm

  class Route < ActiveRecord::Base

    belongs_to :uom
    belongs_to :distance_uom, :class_name => "Uom", :foreign_key => "distance_uom_id"
    belongs_to :location
    belongs_to :departure_location, :class_name => "Location", :foreign_key => "departure"
    belongs_to :destination_location, :class_name => "Location", :foreign_key => "destination"

    has_many :voyages, :dependent => :restrict

    attr_accessible :description, :distance, :distance_uom_id, :departure, :std_consm, :destination, :uom_id

    validates_presence_of :departure, :destination
 end
end



Error :
PG::Error: ERROR:  operator does not exist: integer = character varying
LINE 1: ...NNER JOIN "mdm_locations" ON "mdm_locations"."id" = "mdm_rou...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT COUNT(*) FROM "mdm_routes" INNER JOIN "mdm_locations" ON "mdm_locations"."id" = "mdm_routes"."departure" INNER JOIN "mdm_locations" "destination_locations_mdm_routes" ON "destination_locations_mdm_routes"."id" = "mdm_routes"."destination" WHERE (LOWER(mdm_locations.name) like '%futong%' or LOWER(destination_locations_mdm_routes.name) like '%futong%')

【问题讨论】:

  • 我尝试这个查询 @routes = Route.joins([:departure_location, :destination_location]).where("LOWER(mdm_locations.name) like ? or LOWER(destination_locations_mdm_routes.name) like ?" , "%#{k.downcase}%", "%#{k.downcase}%") 但我得到错误 PG::Error: ERROR: operator does not exist: integer = character varying LINE 1: ...NNER加入 "mdm_locations" ON "mdm_locations"."id" = "mdm_rou...
  • 是的,您绝对应该编辑问题并发布完整的错误。您的评论中没有字符,我们看不到整个错误。
  • 我已经编辑了我的问题,所以这里发生了什么以及如何转换它,因为在 mysql 中没关系

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


【解决方案1】:

你的错误信息说:

运算符不存在:整数 = 字符变化

并指出这部分 SQL:

INNER JOIN "mdm_locations" ON "mdm_locations"."id" = "mdm_routes"."departure"
-- ------------------------------------------------^

结合这些告诉我们mdnm_locations.id 是一个整数(如预期的那样),但mdm_routes.departure 是一个varchar。您不能在 SQL 中比较整数和字符串,除非显式强制转换其中之一以使类型兼容。

您需要修复架构,mdm_routes.departure 应该是整数列,而不是字符串。

MySQL 通过尝试猜测您的意图来尝试变得友好,并让您摆脱许多草率的做法。 PostgreSQL 试图通过强制您准确说出您的意思来避免混淆、错误猜测和隐藏的错误,从而变得友好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2016-12-28
    相关资源
    最近更新 更多