我需要从键值对表中检索具有不同键的3个值。
我的数据库架构如下。我需要通过获取E_SUBID然后使用E_SUBID连接table2,从table1到达table3。一旦table1和table2加入,我需要从table2获取E_CID以将其与table2 E_CID连接以获得“Attr_Value”以保持E_CID作为标准。
表1
------------------------
|E_SUBID| B_LocationID |
|1 100 |
|2 101 |
|3 102 |
表2
-----------------
|E_CID | E_SUBID|
|10 1 |
|11 2 |
|12 3 |
表3
---------------------------------
|E_CID | Attr_name | Attr_Value |
|10 Product Samsung |
|10 Model Smartphone |
|10 usage daily |
|11 Product Apple |
|11 Model Ipad |
|11 usage everyday |
|12 Model smartwatch |
我已成功加入table1,table2和table3,但我无法获得所需的输出,如下所示
输出
|Product | Model | Usage |
Samsung Smartphone daily
Apple Ipad everyday
null smartwatch null
将table1,table2和table3连接起来的查询如下
select distinct t3.Attr_value as Product
from table1 t1, table2 t2, table3 t3
where t1.E_SUBID = t2.E_SUBID and
t2.E_CID = t3.E_CID and
t3.Attr_name=?????
order by Product;
感谢您的时间。
答案 0 :(得分:0)
尝试如下...基本上你试图将行转置到table3中的列。
Select Product, "Model", Usage
From
(
Select
t1.E_SUBID,
t2.E_CID,
Max(Case when T3.Attr_name = 'Product' Then T3.Attr_Value else null end) Product,
max(Case when T3.Attr_name = 'Model' Then T3.Attr_Value else null end) Model,
max(Case when T3.Attr_name = 'Usage' Then T3.Attr_Value else null end) Usage
From Table1 t1,
Table2 t2,
Table3 t3
Where
t1.E_SUBID = t2.E_SUBID
and t2.E_CID = t3.E_CID
group by t1.t1.E_SUBID,t2.E_CID
);
答案 1 :(得分:0)
在这种情况下,您可以根据需要随时加入table3
您希望展示的每个属性name
:
select
p.attr_value product,
m.attr_value "model", -- Quotes to escape reserved word
u.attr_value usage
from table1 t1
join table2 t2 on t1.e_subid = t2.e_subid
left outer join table3 p on t2.e_cid = p.e_cid and p.attr_name = 'Product'
left outer join table3 m on t2.e_cid = m.e_cid and m.attr_name = 'Model'
left outer join table3 u on t2.e_cid = u.e_cid and u.attr_name = 'Usage'
order by 1;
修改强>
根据评论,通过使table3可选(outer join
),查询应返回所有行以及是否已定义Model
或Usage
或Product
。