Chinaunix首页 | 论坛 | 博客
  • 博客访问: 80367
  • 博文数量: 8
  • 博客积分: 186
  • 博客等级: 入伍新兵
  • 技术积分: 142
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-30 12:35
文章分类

全部博文(8)

文章存档

2012年(8)

我的朋友

分类: Mysql/postgreSQL

2012-06-01 01:51:27

我再工作中遇到一个问题,就是一维表如何转换为二维表格。例如有如下数据库表
----------------------
表名:item
id int --主键自动增长
itemName varchar(50)--名称
表名:itemUse
id int --主键自动增长
otherID --其他外键
itemID --item表的外键
value --值
------------------------
itemUse一维表的格式转换为二维表且列出可以通过一条sql语句进行整理

点击(此处)折叠或打开

  1. select a.otherID,b.id as ItemID from
  2.  itemUse a left join item b on 1=1
  3. --这条语句的作用就是每条otherID都生成一条itemID

  4. --在上边的基础上
  5. select a.otherID,a.itemName,b.value from
  6. (select a.otherID,b.id as ItemID,b.itemName from
  7.  itemUse a left join item b on 1=1) a
  8. left join itemUse b on b.otherID=a.otherID and b.itemID=a.ItemID
此时每条otherID的itemName都会列出来,并且还没有某个itemID的otherID也会列出来,但是value值为null,这时就可以通过程序很容易的列出来
阅读(8192) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~