【问题标题】:get the name of the child table when joining multiple tables to a parent table将多个表连接到父表时获取子表的名称
【发布时间】:2021-06-03 12:55:13
【问题描述】:

我有 4 个 postgres 表:

  • 水果的新鲜度 (int) 属性为 1 到 5,序列号为 pk
  • 香蕉的曲率 (int) 从 0 到 360,序列 id pk 既是水果的外键,又是香蕉的主键
  • Apple 与颜色作为文本和相同的 fk pk id
  • 重量为 int 且 fk id 与其他两个相同的菠萝

这是一个水果的例子(你可以想象其他的,它们非常相似):

CREATE TABLE apple
(
    color text,
    id int primary key references fruit(id)
)

以下是我如何在一个查询中获取所有苹果和香蕉:

select * from fruit
natural full join apple
natural full join banana
WHERE (apple.id is NOT NULL OR banana.id IS NOT NULL);

现在我还想在这个查询中添加一个类型字段,这样我就知道哪些是香蕉,哪些是香蕉,哪些是苹果。我知道如果在此特定实例中未定义颜色,我可以检查代码,但稍后可能会有另一种水果也有颜色。我也可以在水果表中使用类型字段,但这将是冗余信息,也没有真正的方法来强制执行关系一致性,这意味着更容易发生错误。
那么有没有办法将子表名添加到结果查询中?

【问题讨论】:

    标签: postgresql join


    【解决方案1】:

    您可以限定每个表列并在 case 语句中检查它们是否为非空

    select *,
      case 
        when apple.id is not null then 'apple' 
        when banana.id is not null then 'banana' 
        else 'i_forgot_to_update_my_query_when_adding_a_new_fruit' 
      end as fruitType
    from fruit
     natural full join apple
     natural full join banana
    WHERE (apple.id is NOT NULL OR banana.id IS NOT NULL);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多