选择2张桌子 [英] Selecting 2 tables

查看:84
本文介绍了选择2张桌子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从具有原始表的另一个表中选择属性

How to select an attribute from another table with the original table

推荐答案

您应该修复数据模型。您应该有三个表:

You should fix the data model. You should have three tables:


  • users :每个用户一行
  • >
  • 个组:每个组一行

  • user_groups :每个用户/组组合一行

  • users: one row per users
  • groups: one row per groups
  • user_groups: one row per user/group combination

对于您的数据模型,我将使用数组取消透视值,然后重新聚合:

With your data model, I would use arrays to unpivot the values and then reaggregate:

我更喜欢使用数组而不是JSON,因此我将使用:

I prefer arrays to JSON, so I would use:

select ug.type,
       (select array_agg(u.name)
        from (unnest(array[ug.user_1, ug.user_2, ug.user_3])) ar(user_id) join
             users u
             on u.user_id = u.id
       ) as users
from user_groups ug;

如果您确实需要JSON,则可以使用JSON函数。

You can use a JSON function if you really want JSON.

这篇关于选择2张桌子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆