db2新手求助

swoky 2009-05-25 12:01:49
有两张表:
product表
productId productName
---------------------------------
1 aaaaaa
2 bbbbbb

productAttribute表
productId attrName attrValue
-----------------------------------------------------
1 size 100
1 color red
1 width 50
*
一个产品有多个属性,现在只要查这三个即可

现在有一个查询要求:
用一个sql(不要存储过程之类的)把这两张表的数据查出来,结果要求如下:
productId productName size color width
--------------------------------------------------------
1 aaaaaaa 100 red 50
2 bbbbb ..........................

另外一个最重要的要求是;productAttribute表中的属性是不定的,比如说color属性,该产品可能没有,所以在productAttribure表中不会存在该条记录, 但是查出来的结果还得有这一列,只是值为null,如下

productId productName size color width
1 aaaaaaa 100 null 50

我这边数据库DB2的,写sql的时候如果能跟数据库搭配最好,
...全文
109 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangxiao_jiang 2009-05-25
  • 打赏
  • 举报
回复
可以实现
select productId,productName ,(select attrValue from productAttribute where productAttribute.productId=productId and attrName='size') as size , (select attrValue from productAttribute where productAttribute.productId=productId and attrName='color') as color, (select attrValue from productAttribute where productAttribute.productId=productId and attrName='width') as width
from product

效率很差。
Herb2 2009-05-25
  • 打赏
  • 举报
回复
好像left join 要改成 left outer join
Herb2 2009-05-25
  • 打赏
  • 举报
回复
product表
productId productName
---------------------------------
1 aaaaaa
2 bbbbbb

productAttribute表
productId attrName attrValue
-----------------------------------------------------
1 size 100
1 color red
1 width 50
--------------------------------------------------------------------------------------
select a.productId,a.productName,b.attrvalue as size,c.attrvalue as color,d.attrvalue as width
from product a
left join (select * from prodeuctattribute where attrname = 'size' ) b on a.productid = b.productid
left join (select * from prodeuctattribute where attrname = 'color' ) c on a.productid = c.productid
left join (select * from prodeuctattribute where attrname = 'width' ) d on a.productid = d.productid
swoky 2009-05-25
  • 打赏
  • 举报
回复
如果不考虑效率方面的问题,可以实现吗
Mr_Bean 2009-05-25
  • 打赏
  • 举报
回复
一般把这种查询定义成为交叉表 而这些一般都不好用一句sql很好的完成 即使完成效率也比较差 要么用报表工具 要么用存储过程 期待有更好的解决方法

5,889

社区成员

发帖
与我相关
我的任务
社区描述
IBM DB2 是美国IBM公司开发的一套关系型数据库管理系统,它主要的运行环境为UNIX(包括IBM自家的AIX)、Linux、IBM i(旧称OS/400)、z/OS,以及Windows服务器版本
社区管理员
  • DB2
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧