【问题标题】:PostgreSQL Return Row if Value Exists in One of Several Columns如果值存在于几列之一中,则 PostgreSQL 返回行
【发布时间】:2018-03-27 21:36:00
【问题描述】:

好的,我坚持这个。

我有一个 PostgreSQL 表 customers,如下所示:

id firm1 firm2 firm3 firm4 firm5 lastname firstname
1  13    8     2     0     0     Smith    John
2  3     2     0     0     0     Doe      Jane

每一行对应一个客户/客户。每个客户/客户可以与一个或多个公司相关联;每个公司#列下的数值对应不同表中的公司ID。

所以我正在寻找一种方法来返回与特定公司关联的所有客户行。

例如,SELECT id, lastname, firstname 其中 8 存在于公司 1、公司 2、公司 3、公司 4、公司 5 将只返回 John Smith 行,因为他在公司 2 列下与公司 8 相关联。

关于如何实现这一点的任何想法?

【问题讨论】:

  • 您应该考虑规范化您的表格。

标签: sql postgresql


【解决方案1】:

您可以为此使用IN 运算符:

SELECT *
FROM customer
where 8 IN (firm1, firm2, firm3, firm4, firm5);

但从长远来看,如果您标准化您的数据模型会更好。

【讨论】:

    【解决方案2】:

    您应该考虑规范化您的表,使用当前架构,您应该加入 firms 表的次数与客户表中公司字段的数量一样多。

    select    *
    from      customers c
    left join firms f1
    on        f1.firm_id = c.firm1
    left join firms f2
    on        f2.firm_id = c.firm2
    left join firms f3
    on        f3.firm_id = c.firm3
    left join firms f4
    on        f4.firm_id = c.firm4
    

    【讨论】:

      【解决方案3】:

      您可以使用arrayunnest 的组合“取消透视”,如以下答案中所述:unpivot and PostgreSQL

      在你的情况下,我认为这应该可行:

      select lastname,
          firstname,
          unnest(array[firm1, firm2, firm3, firm4, firm5]) as firm_id
      from customer
      

      现在您可以从此表中选择(使用with 语句或内部查询),其中firm_id 是您关心的值

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-10
        • 2011-01-31
        • 1970-01-01
        • 2019-02-15
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 2013-08-14
        相关资源
        最近更新 更多