我再工作中遇到一个问题,就是一维表如何转换为二维表格。例如有如下数据库表
----------------------
itemName varchar(50)--名称
表名:itemUse
id int --主键自动增长
otherID --其他外键
itemID --item表的外键
value --值
------------------------
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,这时就可以通过程序很容易的列出来
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/39424/viewspace-1701945/
,如需转载,请注明出处,否则将追究法律责任。