是否可以使用MySQL以这种方式对行进行分组?

时间:2016-01-05 10:38:44

标签: php mysql sql

我有一个像MySQL这样的表:

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

我很好奇是否有一个查询会给我类似的东西:

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

到目前为止,我只是使用以下查询并在循环中对记录进行分组。

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

我尝试使用GROUP,但没有成功。

5 个答案:

答案 0 :(得分:15)

在同一张桌子上使用连接:

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'

结果:

user_id     user_name   user_age
1           ADAM        15
2           EVA         16
3           CRISS       14

答案 1 :(得分:9)

无需使用JOIN。试试这个:

SELECT USER,
       MAX(CASE PARAM WHEN 'NAME' THEN VAL ELSE NULL END) AS NAME,
       MAX(CASE PARAM WHEN 'AGE' THEN VAL ELSE 0 END) AS AGE
FROM test 
GROUP BY USER;

答案 2 :(得分:8)

您可以使用最常用的技术

生成数据透视视图
select
user,
max(case when param = 'NAME' then val end) as name,
max(case when param = 'AGE' then val end) as age
from mytable
group by user

答案 3 :(得分:5)

你可以这样做一个查询:

my $exif_tool = Image::ExifTool->new();
my $info = $exif_tool->ImageInfo('/path/to/image'); #retrieves all image data
# my $info = $exif_tool->ImageInfo('/path/to/image', ['xmp:*']); retrieves only xmp

use Data::Dumper;
warn Dumper $info;

另一种可能性是group_concat,但是你可以在一列中监听所有值。

SELECT t1.user,
        (
           SELECT val FROM tab1 t2 
           WHERE t2.user = t1.user 
             AND t2.param = 'Name'
        ) name,
        (
           SELECT val FROM tab1 t2 
           WHERE t2.user = t1.user 
             AND t2.param = 'Age'
        ) age
    FROM tab1 t1
    GROUP BY user

答案 4 :(得分:3)

您好我在我的db示例中复制了您的问题,请尝试以下查询:

    SELECT t1.USER,VAL,(SELECT VAL AS AGE FROM table1 where USER = t1.USER AND PARAM = 'AGE') as AGE 
    FROM table1 t1
    WHERE param = 'NAME'

或在桌面上使用联接:

SELECT a.USER, a.VAL, b.VAL
FROM table1  t1
INNER JOIN table1 t2 
ON t1.USER = t2.USER
WHERE t1.PARAM = 'NAME'
AND t2.PARAM = 'AGE'

将table1替换为您的表名。