从单个表中分离MySQL中的数据

时间:2015-01-23 16:00:49

标签: mysql

我有这个非常古老而又糟糕的桌子:

meetingid_bigint  key              field_prompt     data_string
1                 meeting_name     Meeting Name     Introduction
1                 location_text    Location Place   Main Office
1                 location_street  Street Address   Street number 1
1                 location_town    Location Town    Town
1                 time_start       Start Time       10.00 AM
2                 meeting_name     Meeting Name     Follow Up
2                 location_text    Location Place   Office
2                 location_street  Street Address   Street number 2
2                 location_town    Location Town    Town 2
2                 time_start       Start Time       1.00 PM
3                 meeting_name     Meeting Name     Introduction
3                 location_text    Location Place   Main Office
3                 location_street  Street Address   Street number 1
3                 location_town    Location Town    Town
3                 time_start       Start Time       8.00 AM

等约有4000条记录。正如您所看到的,同一次会议会一次又一次地出现一个新号码。我想突破meeting_name中的不同location_textlocation_streettime_startdata_string数据,因此我可以将其放在单独的表中并使用FK&#39 ;而是。这张桌子很疯狂。所以问题是,如何在查询中提取具有相同名称和位置的所有会议?唯一的区别是时间。会议名称始终跟随城镇和地址。

输出:

MeetingName      Location     Town      Address 
Introduction     Main Office  Town 1    Street number 1  
Follow Up        Office       Town 2    Street number 2

类似的东西。

修改

谢谢巴兰卡,这有点帮助。

但现在我得到了这个输出:

meetingid_bigint    MeetingName    Location     Town    Address
1                   Introduction
1                                  Main Office
1                                               Town 1
1                                                      
2                   Follow Up
2                                  Office             
2                                                Town 2  
2                                                       Street Number 2
3                                                       Street Number 1
3
3
3                                                Town 1

尝试更改为group by 'MeetingName',然后我几乎按照我想要的方式获得所有会议名称,并且没有dublets,但在位置,城镇或地址中没有任何内容。

select meetingid_bigint
    , case `key` when 'meeting_name' then data_string end as MeetingName
    , case `key` when 'location_name' then data_string end as Location
    , case `key` when 'location_street' then data_string end as Address
from main_meeting_table
group by MeetingName, Town

那段代码给了我MeetingName和Town,但首先是所有的名字,然后是所有的城镇。这是正确的meetingid_bigint所以问题是,我能以某种方式加入这两个吗?

1 个答案:

答案 0 :(得分:0)

你很痛苦。你需要创建一个" pivot"查询。

MySQL不提供构建数据透视查询的内置指令,但您可以手动构建一个:

select meeting_id
     , case `key` when 'meeting_name' then data_string end as MeetingName
     , case `key` when 'location_name' then data_string end as Location
     , case `key` when 'location_street' then data_string end as Address
     -- And so on
from your_table
group by meeting_id;

希望这有帮助。

小评论:避免使用保留关键字(例如key)作为列名称