I have data stored in a MySQL database according to the Entity-Attribute-Value pattern (EAV), specifically user profile values from Drupal 6. I would need an SQL query or view to get the data as a normal relational table. The tables have the following layout:
Table: users
user_id username
---------------------
1 steve
2 michelle
Table: profile_fields
field_id field_name
------------------------
1 first_name
2 last_name
Table: profile_values
field_id user_id value
---------------------------
1 1 Steve
2 1 Smith
1 2 Michelle
2 2 Addams
And I would need to somehow get the following result from a query:
user_id first_name last_name
-----------------------------------
1 Steve Smith
2 Michelle Addams
I have understood this is impossible to do in a single SQL query in the general case. But this is not the general case, and I have two advantages:
This can be done in a sql query using columnar subqueries as follows:
SELECT
u.user_id,
(select value from profile_values f1 WHERE f1.field_id=1 and u.user_id=f1.user_id) AS first_name,
(select value from profile_values f2 WHERE f2.field_id=2 and u.user_id=f2.user_id) AS last_name
FROM users u