ITPub博客

首页 > 数据库 > MySQL > MySQL 之开放架构

MySQL 之开放架构

翻译 MySQL 作者:神谕丶 时间:2014-08-10 00:30:45 0 删除 编辑
此处用到了Pivoting技术
注:Pivoting技术是指一种可以把行转换为列的技术,在Pivoting的执行过程中可能会用到聚合。
这里讨论的都是静态Pivoting查询,即用户需要提前知道旋转的属性列的值,对于动态Pivoting,需要动态地构造查询字符串。


若想对这种架构设计的表进行添加、修改或者删除表和列时,只需要通过insert、update、delete来操作便可完成逻辑架构的更改

但是通过这种方法,可能无法保证其他RDBMS的特性无法使用,比如完整性约束、SQL优化等


首先创建这样的一个表
  1. create table open_schema(
  2. id int,
  3. attribute varchar(10),
  4. value varchar(20),
  5. primary key(id,attribute));







插入以下测试数据


  1. insert into open_schema select 1,'attr1','110930001';
  2. insert into open_schema select 2,'attr1','110930002';
  3. insert into open_schema select 3,'attr1','110930003';
  4. insert into open_schema select 1,'attr2','AAA';
  5. insert into open_schema select 2,'attr2','BBB';
  6. insert into open_schema select 3,'attr2','CCC';
  7. insert into open_schema select 1,'attr3','M';
  8. insert into open_schema select 2,'attr3','M';
  9. insert into open_schema select 3,'attr3','F';
  10. insert into open_schema select 1,'attr4','1990-01-01';
  11. insert into open_schema select 2,'attr4','1990-02-01';
  12. insert into open_schema select 3,'attr4','1990-03-01';
  13. insert into open_schema select 1,'attr5','18600000000';
  14. insert into open_schema select 2,'attr5','18611111111';
  15. insert into open_schema select 3,'attr5','18622222222';


开放架构表open_schema的内容为:(通过select *查询的结果)





如果要查询得出以下结果,需要用到Pivoting技术(需要和聚合一起用)
首先要确定结果的行数和表中行数的关系,对于此表,可以通过id来获得分组:





解决方案:

  1. select id,  max(case when attribute='attr1' then value end) as sno,
  2.             max(case when attribute='attr2' then value end) as name,
  3.             max(case when attribute='attr3' then value end) as sex,
  4.             max(case when attribute='attr4' then value end) as birthdate,
  5.             max(case when attribute='attr5' then value end) as tel
  6. from open_schema
  7. group by id;



来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29773961/viewspace-1248570/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: MySQL range问题
请登录后发表评论 登录
全部评论
微信公众号:神谕的暗影长廊

注册时间:2014-07-28

  • 博文量
    161
  • 访问量
    1195299