如何用 jsonb 类型的 self 列加入一个类

How to join a class with self column of it which is of jsonb type

提问人:yuu Nishinoya 提问时间:7/3/2023 最后编辑:yuu Nishinoya 更新时间:7/3/2023 访问量:27

问:

我有一个名为“School”的类,其架构如下

table "school" do |t|
  t.uuid "school_name"
  t.string "city"
  t.jsonb "students"
end

上表的 student 列为 jsonb 类型。目前我的表格看起来像这样 -

课桌

现在,我想以这样一种方式执行连接,以便我以以下形式获得记录 -

期望的结果

我可以使用雪花中的展平功能来实现这一点 -

select school.*, student.value from school, table(flatten(students)) as student

如何在 psql 或 rails 中的活动记录中执行此操作

我尝试了不同的交叉连接,但没有用。我从 5 小时开始尝试获得所需的结果,但我仍然面临这个问题。

SQL Ruby-on-Rails PostgreSQL ActiveRecord psql

评论


答:

0赞 Les Nightingill 7/3/2023 #1

您的桌子设计应该改变,以便更好地映射现实世界的条件。一个城市可能有很多学校,而一所学校可能有很多学生。因此,适当的关系是:

class City < ApplicationRecord
  # has columns: id, name
  has_many :schools
end

class School < ApplicationRecord
  # has columns id, city_id, name
  belongs_to :city
  has_many :students
end

class Student < ApplicationRecord
  # has columns id, school_id, name, date_of_birth
  belongs_to :school
end

然后,产生所需结果的查询为:

# student.rb
def self.list_all
  select("students.name, students.date_of_birth, schools.name, schools.id, city.name").
  joins(school: :city)
end

顺便说一句,存储学生的年龄是没有意义的,b/c 它会随时间而变化,如果您想在您看来,请从date_of_birth计算。