如何使用 ruby 项目解决 postgresql 中的 AmbiguousColumn 错误

How to solve AmbiguousColumn error in postgresql with ruby project

我想加入两个查询结果。 第一个是

Gig.where(id:gigsInRadioIDS)
When I convert result to json I get this result
[{"id":1,"address":"test1"},{"id":2,"address":"test2"}

第二个是。

Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate))
when I convert result to json I get this result
[{"id":15,"status":"available","gig_id":1}]

我想要的是内连接到结果 所以我希望得到这个结果(我缩写了一些不相关的片段)

[{"id":15,"status":"available","gig_id":1,"id":1,"address":"test1"}]

我试过的是

Gig.where(id:gigsInRadioIDS).as(:tb_gig).join(Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate)), gig_id: :id)

我遇到了这个错误

Sequel::DatabaseError - PG::AmbiguousColumn: ERROR:  column reference "id" is ambiguous
LINE 1: ...) AS "t1" ON ("t1"."gig_id" = "gigs"."id") WHERE ("id" IN (2...

感谢您阅读这段复杂的代码。 任何消息都会有很大帮助。谢谢。

您的 where(id:gigsInRadioIDS) 转换为 WHERE ("id" IN (...)),并且由于演出和插槽都有一个 "id" 列,数据库不知道您想要哪个 ID。

您需要明确指定 table 和 where{{gigs[:id] => gigsInRadioIDS}}

Querying with Sequel

有很多方法可以解决它。看起来您正在查询混合了一些 Gigs 数据的 Slots,因此您可能希望从 Slot 模型开始。常规连接语法更容易理解,并且更容易从两个表中 select 列(即而不是 WHERE fk IN (..))。作为奖励,您可以将 gig_id 过滤器混合到 JOIN 子句中。最后,你不需要使用 Sequel.lit 来做大于/小于你的 WHERE 子句,你应该明确你想要的列 select.

我会这样写:

Slot.join(:gigs, [[:id, :gig_id], [:id, gigsInRadioIDS]])
  .where(status: 'available') { (from() > fromdate) & (to() < todate) }
  .select(Sequel[:slots][:id].as(:slot_id), :status, :gig_id, :address)

获取 .all 条记录并输出 JSON 应该会产生如下结果:

[{"slot_id":15,"status":"available","gig_id":1,"address":"test1"}]

注意 Sequel[:table_name][:column_name] 语法。这是 Sequel 4.49+ 中完全限定标识符的新样式。 (在 Sequel 的过去版本中,它会被写成 :table_name__column_name,但现在不推荐使用这种语法。)