• 阅读<SQL语言艺术>实践五


    【摘抄】
    解决SQL问题时,我们最常碰到的困难是:必须基于"非传统设计(unconventional design)"编程。

    行转成列
    "不可思议的四属性设计"只有entity_id,attribute_key,attribute_type,attribute_value,有时被称为元设计,查询这种表的主要特点是相同表在from子句中被引用非常多次。

    举例说明:
    数据如下
    entity_id ,    attribute_key ,    attribute_type ,    attribute_value
    1 ,            firstname ,        0 ,                    'H'
    1 ,            lastname ,        0 ,                    'ZX'
    1 ,            birthday ,        0 ,                    '1990-1-1'
    2 ,            firstname ,        0 ,                    'L'
    2 ,            lastname ,        0 ,                    'X'
    2 ,            birthday ,        0 ,                    '1998-1-1'

    select a.entity_id personid,
        a.attribute_value firstname ,
        b.attribute_value lastname ,
        c.attribute_value birthday
    From person_att a
    inner join person_att b on a.entity_id = b.entity_id and b.attribute_key = 'lastname'
    inner join person_att c on a.entity_id = c.entity_id and c.attribute_key = 'birthday'
    where a.attribute_key = 'firstname'
    order by a.entity_id

    如果数据属性值的个数不一致,采用left join

    换一个写法:
    select a.entity_id personid,
        max(case when a.attribute_key = 'firstname' then a.attribute_key else '' end) firstname ,
        max(case when a.attribute_key = 'lastname' then a.attribute_key else '' end) lastname ,
        max(case when a.attribute_key = 'birthday' then a.attribute_key else '' end) birthday ,
    From a_kv a
    group by a.entity_id
    order by a.entity_id

    从效果上来说,一致的;
    从执行效率上说,后一种效率要高些。数据越大效果越明显

    个人观点:
    少用四属性设计,缺点明显:
    1、字段类型都是固定的,特别在value字段上,如上,birthday应该是时间类型。对提取和判断比对都需要转换类型
    2、无法从数据库上验证信息正确。

    当然,也有好处:保存方便统一。

    使用建议:
    苦下功夫设计数据库结构,对常用和固定表使用固定设计-该什么类型就什么类型
    实在需要此类“四属性设计”,建议能确定所有key对应的value都是同一类型;要么全部字符串,要么全部数字等。不要出现上例情况

    对于四属性设计的字段获取,建议采用外部遍历方式提取

    实际应用更应注意DB设计规范~~

  • 相关阅读:
    gulp的使用
    Js中call(),apply()的使用
    HTML中<meta>标签的使用
    字符串及数组常用方法
    css—transform
    《Java设计模式》——适配器模式
    全文检索工具包Lucene以及企业及应用Solr的学习(二)—— solr中edismax用到的Query Function以及java扩展
    全文检索工具包Lucene以及企业及应用Solr的学习(一)
    最近发现服务器发生了一些问题
    TxT读取写入
  • 原文地址:https://www.cnblogs.com/GoGoagg/p/1942994.html
Copyright © 2020-2023  润新知