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

本文探讨了四属性设计在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设计规范~~

转载于:https://www.cnblogs.com/GoGoagg/archive/2011/01/24/1942994.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值