我有3张桌子:
Productmaster:
ProductId PName PDescription
属性:
AttributeID attName
---- ----
1 Brand
2 Category
3 Artist
ProductAttributeValues
paId ProductId AttributeID AttributeValues
product
可以有多个attributes
。
这是所需的输出:
ProductId ProductDesc Brand Category Artist
--- --- --- --- ---
1 sadasd Brand1 Category1 Artist1
2 sadasds Brand2 Category3 Artist4
如何获得此输出?
提前致谢。
答案 0 :(得分:1)
您应该为要引入的每个属性值保留连接,例如
select p.ProductId,p.ProductDesc,
a1.AttributeValues as Brand,
a2.AttributeValues as Category,
a3.AttributeValues as Artist,
from Product p
left join ProductAttributeValues a1 on(p.ProductId=a1.ProductId and a1.AttributeID=1)
left join ProductAttributeValues a2 on(p.ProductId=a2.ProductId and a2.AttributeID=2)
left join ProductAttributeValues a3 on(p.ProductId=a3.ProductId and a3.AttributeID=3)
要把它变成英文,“给我所有产品,如果它们存在,给我一个品牌,类别和艺术家属性”
我假设产品每个属性只有一个或零值。
答案 1 :(得分:1)
假设每个产品的每个属性只出现一次:
SELECT
pm.ProductId as ProductId,
pm.PDescription as ProductDesc,
pav_Brand.AttributeValues as Brand,
pav_Category.AttributeValues as Category,
pav_Artist.AttributeValues as Artist
FROM
ProductMaster pm
inner join ProductAttributeValues pav_Brand
on pm.productId == pav_Brand.ProductId
inner join Attributes a_Brand
on pav_Brand.AttributeId = a_Brand.AttributeId
AND a_Brand.attName = 'Brand'
inner join ProductAttributeValues pav_Category
on pm.productId == pav_Category.ProductId
inner join Attributes a_Category
on pav_Category.AttributeId = a_Category.AttributeId
AND a_Brand.attName = 'Category'
inner join ProductAttributeValues pav_Artist
on pm.productId == pav_Artist.ProductId
inner join Attributes a_Artist
on pav_Category.AttributeId = a_Artist.AttributeId
AND a_Brand.attName = 'Artist'
如果数据并非始终可用,则可以使用左外连接。
答案 2 :(得分:0)
尝试此查询,可能需要一些调整
Select pm.ProductId, pm.PDescription, pav1.AttributeValues, pav2.AttributeValues, pav3.AttributeValues
from Productmaster pm, ProductAttributeValues pav1, ProductAttributeValues pav2, ProductAttributeValues pav3
where pm.ProductId = pav1.ProductId
and pav1.AttributeID = 1
and pm.ProductId = pav2.ProductId
and pav2.AttributeID = 2
and pm.ProductId = pav3.ProductId
and pav3.AttributeID = 3
答案 3 :(得分:0)
SELECT ProductId, ProductDesc,
(
SELECT AttributeValues
FROM ProductAttributeValues pv
WHERE pv.AttributeID = 1
AND pv.ProductID = p.ProductID
) AS Brand,
(
SELECT AttributeValues
FROM ProductAttributeValues pv
WHERE pv.AttributeID = 2
AND pv.ProductID = p.ProductID
) AS Category,
(
SELECT AttributeValues
FROM ProductAttributeValues pv
WHERE pv.AttributeID = 3
AND pv.ProductID = p.ProductID
) AS Artist
FROM Products p