ruby-on-rails - 如何(通过关系表)加入针对自身的表?

标签 ruby-on-rails postgresql

考虑下表:

人:

id: integer
name: string

friend :

id1: integer
id2: integer

我想找到所有的 friend 对,所以我使用这样的东西:

People.joins("JOIN friends ON friend.id1 = people.id JOIN friends ON friend.id2 = people.id")

生成此 SQL:

SELECT "people".* FROM "people" 
JOIN friends ON friends.id1 = people.id 
JOIN people ON friends.id2 = people.id

并出现以下错误:

(pry) output error: #<ActiveRecord::StatementInvalid:
PG::DuplicateAlias: ERROR:  table name "people" specified more than once

多次指定 people 有什么问题?

最佳答案

给他们不同的别名:

SELECT p1.* FROM people p1
JOIN friends ON friends.id1 = p1.id 
JOIN people p2 ON friends.id2 = p2.id

关于ruby-on-rails - 如何(通过关系表)加入针对自身的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865637/

相关文章:

ruby-on-rails - validates_related 不检查关联的存在

ruby-on-rails - 寻找网络 pdf 查看器,而不是 google 文档查看器

postgresql - 使用 "SELECT DISTINCT"时如何保留额外的 key ?

PostgreSQL - 如何将函数的参数传递给触发器?

sql - 如何在postgresql中对json类型使用唯一约束

sql - 在 Postgres 中使用计算数据结构更新 JSONB 字段

ruby-on-rails - Rails 接受_nested_attributes_for 回调

ruby-on-rails - Prawn 和 Prawn Rails PDF 生成 - UTF-8?

ruby-on-rails - 在我对寄存器文件进行任何更改之前,关联的(动态)范围不起作用

node.js - 在 NodeJS 中向外行用户隐藏 Web 服务