【问题标题】:ID column with generated uniqe values in view (with union all)在视图中具有生成的唯一值的 ID 列(全部联合)
【发布时间】:2020-04-22 11:56:03
【问题描述】:

我对脚本创建的数据库有看法:

create or replace view auction_view4 as
    select row_number() over(order by f.userid) as id, f.id as propertyId,f.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, f.price, f."size", f.rooms, f.floor 
    from address a, flat f, realassets r
    where f.addressid = a.id and a.realassetid =r.id 
    union all
    select row_number() over(order by p.userid) as id, p.id as propertyId, p.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, p.price, p."size", null as rooms, null as floor 
    from address a, plot p, realassets r
    where p.addressid = a.id and a.realassetid =r.id 
    union all
    select row_number() over(order by h.userid) as id, h.id as propertyId, h.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, h.price, h."size", h.rooms, null as floor
    from address a, house h, realassets r
    where h.addressid = a.id and a.realassetid =r.id 

这是我的观点

一切正常,但我在想如何生成具有唯一值的 ID 列? 您对如何实现该目标有任何建议吗?

【问题讨论】:

    标签: database postgresql view


    【解决方案1】:

    你可以试试这样的

    create or replace view auction_view4 as
        with data as (
        select f.id as propertyId,f.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, f.price, f."size", f.rooms, f.floor 
        from address a, flat f, realassets r
        where f.addressid = a.id and a.realassetid =r.id 
        union all
        select p.id as propertyId, p.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, p.price, p."size", null as rooms, null as floor 
        from address a, plot p, realassets r
        where p.addressid = a.id and a.realassetid =r.id 
        union all
        select  h.id as propertyId, h.userid, r."type", a.street, a.homenumber, a.localnumber, a.city, a.postcode, h.price, h."size", h.rooms, null as floor
        from address a, house h, realassets r
        where h.addressid = a.id and a.realassetid =r.id )
    select row_number() over(order by userid), * from data
    

    但是这种方法的缺点是同一条记录在两个连续查询中可能具有不同的 id(例如,因为您在涉及的某个表中插入了一个新的用户 ID)。

    另一种方法可以从两列或更多列生成哈希:

    select ..., md5(f.userid || r.type) ...
    

    但是虽然您已经解决了两个不同查询之间 id 唯一性的问题,但如果您必须将 id 用作搜索字段、过滤器或索引,您将面临性能问题

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 1970-01-01
      • 2012-11-17
      • 2011-06-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      相关资源
      最近更新 更多