将产品属性表与产品表连接以显示产品

时间:2015-06-13 10:06:58

标签: mysql sql database join left-join

我有三个表用于列出具有产品属性的产品

带有虚拟数据的

产品表

enter image description here

enter image description here

带有虚拟数据的

Product_Attributes

enter image description here

enter image description here

带有虚拟数据的

属性

enter image description here

enter image description here

Kespersky antivirus(productid = 1)没有属性,但iPhone(productid = 2)有两个适用于它的属性,内存和分辨率都在属性表中,其值存储在 Product_Attribute 表。

如何连接这些表格以显示/显示具有相应属性的产品?

修改

我需要将这些产品显示为

enter image description here

4 个答案:

答案 0 :(得分:5)

以下内容适用于任意数量的属性:

select product.productId, product.name,
group_concat(concat(attr.attributeName, ":", pa.attributeValue))
from product
left outer join product_attributes pa 
on (pa.productId = product.productId)
left outer join attributes attr 
on (attr.attributeId = pa.attributeId)
group by product.productId, product.name

答案 1 :(得分:4)

您的问题需要一个需要预先定义的数据透视表。这意味着,如果要在结果集中包含2个额外的COLUMNS,则查询最多只能存储2个属性。这是PRESENTATION图层问题,而不是查询图层。但是,唉,我有一个通用的解决方案。它假设您将拥有最多2个属性(由于上述原因)。这是查询:

SELECT 
  P.ProductName,
  A.AttributeName,
  PA.AttributeValue,
  B.AttributeName,
  PB.AttributeValue
FROM lb_products P
LEFT JOIN (select row_number() over (partition by productID order by AttributeID asc) rn, * 
           from lb_product_attributes x) PA
  ON P.ProductID = PA.ProductID and PA.rn = 1
LEFT JOIN (select row_number() over (partition by productID order by AttributeID asc) rn, * 
           from lb_product_attributes x) PB
  ON P.ProductID = PB.ProductID and PB.rn = 2
LEFT JOIN lb_attributes A
  ON PA.AttributeID = A.AttributeID
LEFT JOIN lb_attributes B
  ON PB.AttributeID = B.AttributeID;

和SQL小提琴让你玩。祝好运!随时问任何问题:)

http://sqlfiddle.com/#!6/49a9e0/5

答案 2 :(得分:3)

你可以试试这个:

SELECT 
  P.ProductName,
  P.Price,
  -- Add other Column Here
  A.AttributeName,
  PA.AttributeValue
FROM Product P
LEFT JOIN Product_Attributes PA
  ON P.ProductID = PA.ProductID
LEFT JOIN Attributes A
  ON PA.AttributeID = A.AttributeID

<强>输出

ProductName   Price    AttbituteName    AttributeValue
Kaspersky     380      NULL             NULL   
IPHONE        45000    Memory           64 gb
IPHONE        45000    Resolution       21500 pi

答案 3 :(得分:2)

Philip's答案肯定是好的,他解释了这个问题,因为如果你正在做一个支点,你需要定义一个静态数量的属性。我不确定窗口功能是否必要,所以我的方法就是这样:

select
  prd.productId
  ,max(case when lpa.attributeId = 1 then attributeName else null end) attributeName1
  ,max(case when lpa.attributeId = 1 then attributeValue else null end) attributeValue1
  ,max(case when lpa.attributeId = 2 then attributeName else null end) attributeName2
  ,max(case when lpa.attributeId = 2 then attributeValue else null end) attributeValu2
from
  lb_products prd
  left outer join lb_product_attributes lpa on lpa.productId = prd.productId
  left outer join lb_attributes atr on atr.attributeId = lpa.attributeId
group by
  prd.productId