原始SQL语句无效

时间:2016-05-30 14:44:52

标签: sql postgresql pg

如果此查询将在Rails ORM中完成,则它看起来像

ids = User.find(user_id).conversations.pluck(:id)
UserMessage.where("'conversation'.'id' IN (?)", ids)

我的模特是:

class User
  has_many :conversations, through: :user_conversations
end

class UserMessage
  belongs_to :user
  belongs_to :conversation
end

在原始SQL中:

ActiveRecord::Base.connection.execute(
%( SELECT "user_messages".*,
    ( SELECT array_agg(t) 
      FROM (
      SELECT "conversations"."id"
      FROM "conversations"
      INNER JOIN "users_conversations" ON "conversations"."id" = "users_conversations"."conversation_id"
      WHERE "users_conversations"."user_id" = 'f044e064-0b6f-4371-91aa-3c03e31c8ad8'
     ) t
      ) AS this_user_conversations
   FROM "user_messages"
   WHERE "user_messages"."conversation_id" IN (this_user_conversations)))

这给出了

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "this_user_conversations" does not exist
LINE 11: WHERE "user_messages"."conversation_id" IN (this_user_conver...

但据我所知,此查询使用AS语句定义此值。

1 个答案:

答案 0 :(得分:0)

where子句发生在select列表之前,因此无法查看子查询。另一种选择:

select
    um.*, tuc.this_user_conversations
from
    "user_messages" um
    inner join
    (
        select array_agg(c."id") as this_user_conversations
        from
            "conversations" c
            inner join
            "users_conversations" uc on c."id" = uc."conversation_id"
        where uc."user_id" = 'f044e064-0b6f-4371-91aa-3c03e31c8ad8'
    ) tuc on um."conversation_id" = any (tuc.this_user_conversations)