【问题标题】:Retrieve custom table data检索自定义表数据
【发布时间】:2020-07-13 08:36:51
【问题描述】:

我有一个场景,其中我有三个表custom_tablescustom_fieldscustom_field_values,多个过滤条件将应用于存储在custom_field_values 中的值。我们在custom_field_values 中有entity_id,它是标识每一行的唯一标识符,简单来说entity_id 代表普通表中的一行。这是带有示例的表格,

现在,我的条件是age > 25,在这种情况下,它只删除custom_field_values 表中的第三行,而我想删除custom_field_values 中具有相同entity_id 示例的整个记录​​@ 第三行不是根据我们的条件为真,它的 entity_id 是12345,所以我想用这个entity_id 取消选择所有记录,我期待这样的结果,

我无法实现这一目标,我正在寻找一些通用且最快的方法来实现这一目标,因为自定义表可以有超过 100 万条记录,任何人都可以帮助...请...

【问题讨论】:

    标签: sql ruby-on-rails database postgresql


    【解决方案1】:

    这是糟糕的设计,无论你做什么都不会很快,尤其是你期望的行数,维护将是一场噩梦并且容易出错。您最好的选择是重新设计以结束 1 张桌子。因为我不知道 custom_tables 表的功能是什么,所以我只是使用其他的。因此,如果只使用另外 2 个,您将拥有:

    create table custom_tables (
                 id            bigserial 
               , entity_id     text        -- or integer/bigint if appropriate
               , name          text
               , age           integer
               ) ;
    

    如果你坚持这种(荒谬的)设计,那么至少创建一个基本上映射到上表的视图;或者更好的物化视图如下:

    create or replace view custom_tables_set as
       with id_fld as 
             ( select cfv.entity_id, cfv.value id
                  from custom_field_values cfv
                  left join custom_fields  cf  on(cf.id = cfv.custom_field_id)
                 where cf.alias = 'id'
              ) 
           , name_fld as
             ( select cfv.entity_id, cfv.value as name 
                  from custom_field_values cfv
                  left join custom_fields  cf  on(cf.id = cfv.custom_field_id)
                 where cf.alias = 'name'
              )  
           , age_fld as  ( select cfv.entity_id, cfv.value age  
                  from custom_field_values cfv
                  left join custom_fields  cf  on(cf.id = cfv.custom_field_id)
                 where cf.alias = 'age'
              )  
       select i.entity_id, i.id, n.name, a .age 
         from id_fld  i 
         left join name_fld n on n.entity_id = i.entity_id
         left join age_fld  a on a.entity_id = i.entity_id ;  
    

    您需要为您创建的每个别名值添加其他 .._fld CTE。

    至少在视图中,您不会在您编写的每个查询中加入。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 2015-09-10
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      相关资源
      最近更新 更多