Sql 查询属性,其中缺少一个属性
我有一个问题要问。 有两个表格:Sql 查询属性,其中缺少一个属性,sql,join,Sql,Join,我有一个问题要问。 有两个表格: Objects table: ============== Object ID Date 1 2016-03-15 2 2016-01-20 Attributes table: ================= Parent ID Attribute AttributeData 1 Size XL 2 Size S 2 Price 20 The
Objects table:
==============
Object ID Date
1 2016-03-15
2 2016-01-20
Attributes table:
=================
Parent ID Attribute AttributeData
1 Size XL
2 Size S
2 Price 20
The query is to join the data to get this:
==========================================
Objet ID Size Price
1 XL NULL
2 S 20
But I only get this:
==========================================
Objet ID Size Price
2 S 20
左连接没有帮助-因为属性表中没有ID1的price条目
我很抱歉在这件事上加入了这么一个新手
很高兴能得到任何帮助
Steffen我认为条件聚合可以满足您的要求:
select parentid,
max(case when attribute = 'Size' then attributedata end) as size,
max(case when attribute = 'Price' then attributedata end) as price
from attributes
group by parentid;
使用左连接
可以执行以下操作:
select o.*, s.attributedata as size, p.attributedata as price
from objects o left join
attributes s
on o.objectid = s.parentid and s.attribute = 'Size' left join
attributes p
on o.objectid = p.parentid and p.attribute = 'Price';
请注意,要使其起作用,属性名称上的条件需要在
on
子句中,而不是where
子句中。我认为条件聚合可以满足您的要求:
select parentid,
max(case when attribute = 'Size' then attributedata end) as size,
max(case when attribute = 'Price' then attributedata end) as price
from attributes
group by parentid;
使用左连接
可以执行以下操作:
select o.*, s.attributedata as size, p.attributedata as price
from objects o left join
attributes s
on o.objectid = s.parentid and s.attribute = 'Size' left join
attributes p
on o.objectid = p.parentid and p.attribute = 'Price';
请注意,要使其起作用,属性名称上的条件必须在
on
子句中,而不是where
子句中。请发布现有查询。请澄清您使用的数据库,因为这将影响答案。请发布您现有的查询。还请澄清您使用的数据库,因为这将影响答案。