SQL query to view EAV data as 3NF? (Drupal 6 profile values)
-
01-06-2021 - |
문제
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:
- I know the content of the "profile_fields" table, and I am 100% sure that this data will not change for the time period that this query will be used.
- It doesn't have to be in a single query - it can be a query, some PHP code to analyze the results and then another query.
해결책
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
제휴하지 않습니다 StackOverflow