1

I have 3 tables, User, Attributes, and UserAttributes.

User
+----+-------+
| Id | Email |
+----+-------+
|  1 | a@b.c |
|  2 | b@c.d |
|  3 | c@d.e |
+----+-------+

Attributes
+----+-----------+
| Id | Attribute |
+----+-----------+
|  1 | name      |
|  2 | gender    |
|  3 | age       |
+----+-----------+

UserAttributes
+--------+--------+--------+
| UserId | AttrID | Value  | 
+--------+--------+--------+
|  1     | 1      | Foo    |
|  1     | 2      | Male   |
|  1     | 3      | 21     |
|  2     | 1      | Bar    |
|  2     | 2      | Female |
|  3     | 1      | FooBar |
|  3     | 2      | Male   |
|  3     | 3      | 25     |
+--------+--------+--------+

I need a query to return data where the column names are the attributes from Attributes table.

+-------+--------+--------+-----+
| Email | Name   | Gender | Age |
+-------+--------+--------+-----+
| a@b.c | Foo    | Male   | 21  |
| b@c.d | Bar    | Female | NULL|
| c@d.e | FooBar | Male   | 25  |
+-------+--------+--------+-----+

I looked at this: need to convert data in multiple rows with same ID into 1 row with multiple columns and this: combined rows with same id in to one row keeping all data

But the answer seems little bit confusing, and there is no third table involved.

Amil Osmanli
  • 125
  • 6
  • 4
    If you want a query that has column names that come from a table, then you want a dynamic pivot. Google: "mysql dynamic pivot". – Gordon Linoff Feb 02 '16 at 11:57

0 Answers0