将存储为行的名称值对转换为列

时间:2018-09-17 09:47:30

标签: mysql sql join select

我有一张桌子,如下:

ID  | FieldName     | FieldValue
--------------------------------
01  | event_name    | Event Title
01  | event_cost    | 10.00
01  | event_loc     | Leeds
02  | event_name    | Another Event
02  | event_cost    | 15.00
02  | event_loc     | London

我想查询这个并返回结果,如下所示:

Title           | Cost  | Location
------------------------------------
Event Title     | 10.00 | Leeds
Another Event   | 15.00 | London

什么是最好的方法?我已经尝试过使用SELECT查询,但是我只能返回一个字段值,而且似乎无法加入它们。

5 个答案:

答案 0 :(得分:3)

您可以进行有条件的聚合:

select max(case when FieldName = 'event_name' then FieldValue end) as Title,
       max(case when FieldName = 'event_cost ' then FieldValue end) as Cost,
       max(case when FieldName = 'event_loc' then FieldValue end) as Location
from table t
group by id;

答案 1 :(得分:1)

用例何时

select id, max( case when FieldName='event_name' then FieldValue end) as Title,
max(case when FieldName='event_cost' then FieldValue end) as cost,
max(case when FieldName='event_loc' then FieldValue end) as Location from t
group by id

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=940326493ef7b561375953f85f65a4ea

id  Title   cost    Location
1   Event Title     10.0    Leeds
2   Another Event   15.0    London

答案 2 :(得分:1)

使用条件聚合。如果特定字段名称有多个匹配项,则GROUP_CONCAT可用于返回逗号分隔的列表。

SELECT
    ID,
    GROUP_CONCAT(CASE WHEN FieldName = 'event_name' THEN FieldValue END) AS Title,
    GROUP_CONCAT(CASE WHEN FieldName = 'event_cost' THEN FieldValue END) AS Cost,
    GROUP_CONCAT(CASE WHEN FieldName = 'event_loc'  THEN FieldValue END) AS Location
FROM yourdata
GROUP BY ID

答案 3 :(得分:1)

尝试此查询:

SELECT event_name AS 'Title', event_cost AS 'Cost', event_loc AS 'Location' 
FROM yourTableName

答案 4 :(得分:0)

用例when和聚合:

select max(case when fieldname='event_name' then FieldValue) as title,
max(case when fieldname='event_cost' then FieldValue) as cost,
max(case when fieldname='event_loc' then FieldValue) as location,
from tablename group by id