Question

I am building a database schema of customers & rather than forever adding columns over time, I would prefer to use the EAV (entity attribute value) Magento-style of having this data stored in other tables and linked up.

My SQL Fiddle will give a better idea of the structure http://sqlfiddle.com/#!2/82a70

In this instance I would want to generate a query that displays all the customers with their relevant information that is stored in the other tables, if for example a customer hasn't got a value for a particular entity it just displays NULL.

e.g My output that I would want to display is as follows:

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

Can anyone suggest the most optimised MySQL query to produce this recordset on the basis there could be many more entities or attributes added later on?

Was it helpful?

Solution

This type of SQL query will produce the table you're looking for, but you will have to generate this query dynamically based on the contents of your 'eav_attribute' table.

As KM said, each attribute requires another 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
;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top