我再工作中遇到一个问题,就是一维表如何转换为二维表格。例如有如下数据库表
- 表名:item
- id int --主键自动增长
- itemName varchar(50)--名称
- 表名:itemUse
- id int --主键自动增长
- otherID --其他外键
- itemID --item表的外键
- value --值
- --可以将itemID看成otherID的属性,此时itemUse为一维表
itemUse一维表的格式转换为二维表且列出可以通过一条sql语句进行整理
- select a.otherID,b.id as ItemID from
- itemUse a left join item b on 1=1
- --这条语句的作用就是每条otherID都生成一条itemID
- --在上边的基础上
- select a.otherID,a.itemName,b.value from (select a.otherID,b.id as ItemID,b.itemName from
- itemUse a left join item b on 1=1) a left join itemUse b on b.otherID=a.otherID and b.itemID=a.ItemID
此时每条otherID的itemName都会列出来,并且还没有某个itemID的otherID也会列出来,但是value值为null,这时就可以通过程序很容易的列出来