EAV建模数据库模式 - 查询建议

时间:2014-05-01 13:23:41

标签: mysql database database-design schema entity-attribute-value

我正在构建一个客户数据库架构&而不是永远添加列随着时间的推移,我宁愿使用EAV(实体属性值)Magento风格将这些数据存储在其他表中并链接起来。

我的SQL小提琴将更好地了解结构 http://sqlfiddle.com/#!2/82a70

在这种情况下,我想生成一个查询,显示存储在其他表中的所有客户及其相关信息,例如,如果客户没有为其显示的特定实体获取值NULL。

例如我想要显示的输出如下:

customer_id | first_name |  surname  | profession | club
      1          bob        geldof       singer      NULL
      2         lionel       messi      footballer   barcelona fc

有人可以建议最优化的MySQL查询来生成此记录集,因为可能会在以后添加更多实体或属性吗?

1 个答案:

答案 0 :(得分:1)

这种类型的SQL查询将生成您正在寻找的表格,但您必须根据“eav_attribute”的内容动态生成此查询。表

正如KM所说,每个属性都需要另一个LEFT JOIN

SELECT
  customer_entity.customer_id AS customer_id,
  name.value AS firstname, 
  surname.value AS surname,
  profession.value AS profession,
  club.value AS club
FROM customer_entity
  LEFT JOIN customer_varchar AS name
    ON name.entity_id = customer_entity.customer_id AND name.attribute_id = 1
  LEFT JOIN customer_varchar AS surname
    ON surname.entity_id = customer_entity.customer_id AND surname.attribute_id = 2
  LEFT JOIN customer_varchar AS profession
    ON profession.entity_id = customer_entity.customer_id AND profession.attribute_id = 3
  LEFT JOIN customer_varchar AS club
    ON club.entity_id = customer_entity.customer_id AND club.attribute_id = 4
;