Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to group rows this way using MySQL?

Tags:

I have a MySQL table like:

ID, USER, PARAM, VAL
--------------------
1 | 1 | NAME | ADAM
2 | 1 | AGE  | 15
3 | 2 | NAME | EVA
4 | 2 | AGE  | 16
5 | 3 | NAME | CRISS
6 | 3 | AGE  | 14

And I'm curious if there is a query which would give me something similar to:

1 | ADAM | 15
2 | EVE  | 16
3 | CRISS| 14

So far I'm just using the below query and grouping the records in a loop.

SELECT * FROM table WHERE PARAM ='NAME' OR PARAM = 'AGE'

I tried to use GROUP but without success.

like image 796
Adam Bieńkowski Avatar asked Jan 05 '16 10:01

Adam Bieńkowski


1 Answers

Use join on the same table:

SELECT a.USER user_id, a.VAL user_name, b.VAL user_age
FROM `table` a
INNER JOIN `table` b ON a.USER = b.USER
WHERE a.PARAM = 'NAME'
AND b.PARAM = 'AGE'

Result:

user_id     user_name   user_age
1           ADAM        15
2           EVA         16
3           CRISS       14
like image 75
n-dru Avatar answered Oct 20 '22 16:10

n-dru