阅读<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设计规范~~

posted @ 2011-01-24 11:47  西就东城  阅读(198)  评论(0编辑  收藏  举报