SQL:数据被分成多行

时间:2014-08-29 09:11:42

标签: mysql sql osticket

我遇到的问题是,我试图将一个链接到ID的列中的数据导出到另外3列,但是我最终得到了大量的NULLS和多个相同的IDS,如下图所示。

我有一个包含4列的表,在这些列中,数据以非常奇怪的方式存储。 我的表看起来像这样

entry_id| field_id |      value                 | value_ID |
|    480|       -5 |      string of text| 10    |
|    480|      -20 |      string of other text  | 10       | 
|    480|      -23 |      Yes                   | 10       |
|    480|      -22 |      No                    | 10       |

我设计了一个查询,将字段ID转换为带有附加值的新列。

查询如下所示:

 SELECT 
 ticket.ticket_id,
 ticket.number,
 users.name,

 CASE WHEN val.field_id IN (5) THEN val.value end as "Issue Summary",
 CASE WHEN val.field_id IN (20) THEN val.value end as "Project Site",
 CASE WHEN val.field_id IN (23) THEN val.value end as "Action"

 FROM ost_ticket ticket

 LEFT JOIN ost_form_entry entry ON (ticket.ticket_id = entry.object_id)
 LEFT JOIN ost_form_entry_values val ON (entry.id = val.entry_id)
 LEFT JOIN ost_user users ON (ticket.user_id = users.id)
 LEFT JOIN ost_form_field fields ON (val.field_id = fields.id)

此查询返回:  http://i.stack.imgur.com/hqBv0.png(由于缺乏声誉而无法嵌入图片。)

正如您所看到的,我有多个相同的机票ID'还有很多NULLS。我应该使用什么查询,每个唯一的ticket_id只有一行

1 个答案:

答案 0 :(得分:0)

我猜你想要的是在一行中获取字段值:

SELECT 
 ticket.ticket_id,
 ticket.number,
 users.name,
 issue_sum.value as "Issue Summary",
 project_site.value as "Project Site",
 action.value as "Action"
 FROM ost_ticket ticket
 LEFT JOIN ost_form_entry entry ON (ticket.ticket_id = entry.object_id)
 LEFT JOIN ost_form_entry_values issue_sum 
     ON (entry.id = issue_sum.entry_id) and issue_sum.field_id = 5
 LEFT JOIN ost_form_entry_values project_site 
     ON (entry.id = project_site .entry_id) and project_site.field_id = 20 
 LEFT JOIN ost_form_entry_values action 
     ON (entry.id = action.entry_id) and action.field_id = 23
 LEFT JOIN ost_user users ON (ticket.user_id = users.id)
 LEFT JOIN ost_form_field fields ON (val.field_id = fields.id)

鉴于每张票可以有多个实体记录,我只能建议使用聚合:

  SELECT 
     ticket.ticket_id,
     ticket.number,
     users.name,
     MAX(issue_sum.value) as "Issue Summary",
     MAX(project_site.value) as "Project Site",
     MAX(action.value) as "Action"
     FROM ost_ticket ticket
     LEFT JOIN ost_form_entry entry ON (ticket.ticket_id = entry.object_id)
     LEFT JOIN ost_form_entry_values issue_sum 
         ON (entry.id = issue_sum.entry_id) and issue_sum.field_id = 5
     LEFT JOIN ost_form_entry_values project_site 
         ON (entry.id = project_site .entry_id) and project_site.field_id = 20 
     LEFT JOIN ost_form_entry_values action 
         ON (entry.id = action.entry_id) and action.field_id = 23
     LEFT JOIN ost_user users ON (ticket.user_id = users.id)
     LEFT JOIN ost_form_field fields ON (val.field_id = fields.id)
GROUP BY  
     ticket.ticket_id,
     ticket.number,
     users.name;