0

I have table like this:

uid | fid | value
1   | 1   | nameOf1
1   | 2   | surnameOf1
1   | 3   | countryOf1
2   | 1   | nameOf2
2   | 2   | surnameOf2

And need to transform/select it like this:

uid | name    | surname    | country
1   | nameOf1 | surnameOf1 | countryOf1
2   | nameOf2 | surnameOf2 | ..
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • possible duplicate of [mysql pivot query results with GROUP BY](http://stackoverflow.com/questions/6605604/mysql-pivot-query-results-with-group-by) – Ben Nov 17 '13 at 15:29

2 Answers2

1

Try something like:

SELECT t1.uid, t2.value AS name, t3.value AS surname, t4.value AS country FROM table t1
  LEFT JOIN table t2 on t2.uid = t1.uid AND t2.fid = 1
  LEFT JOIN table t3 on t3.uid = t1.uid AND t3.fid = 2
  LEFT JOIN table t4 on t4.uid = t1.uid AND t4.fid = 3
  GROUP BY t1.uid;

or:

SELECT DISTINCT t1.uid, t2.value AS name, t3.value AS surname, t4.value AS country FROM table t1
  LEFT JOIN table t2 on t2.uid = t1.uid AND t2.fid = 1
  LEFT JOIN table t3 on t3.uid = t1.uid AND t3.fid = 2
  LEFT JOIN table t4 on t4.uid = t1.uid AND t4.fid = 3;
Alex
  • 1,605
  • 11
  • 14
  • I have made a test with 280,000 records (20% of countries are empty). Without indexes both queries are too slow. They almost do not work. Then I created a primary index on two columns: uid and fid. And both queries work more or less fast. – Alex Nov 17 '13 at 20:49
0

It's a little complex, but you could do something like:

select distinct uid as uid,
   (select value from dataTable as table1 
           where table1.uid=dataTable.uid and fid = 1) as name,
   (select value from dataTable as table2 
           where table2.uid=dataTable.uid and fid = 2) as surname,
   (select value from dataTable as table3 
           where table3.uid=dataTable.uid and fid = 3) as country
from dataTable group by uid

SQLFiddle

Brian Hoover
  • 7,861
  • 2
  • 28
  • 41