MySQL检索行并将它们转换为列

时间:2015-01-09 13:20:09

标签: mysql sql select join pivot

我正在使用以下查询返回表单ID及其附件ID。每个表单都没有附件,一个附件或两个附件。

SELECT form.id       AS 'Form ID', 
       attachment.id AS 'Attachment ID' 
FROM   form, 
       attachment 
WHERE  form.id = attachment.form_id; 

我正在检索结果如下:

+---------+---------------+
| Form ID | Attachment ID |
+---------+---------------+
| 1       | 1             |
| 1       | 2             |
| 2       | 3             |
| 3       | 4             |
| 5       | 5             |
| 5       | 6             |
| 6       | 7             |
+---------+---------------+

我正试图找出一种检索结果的方法,如下所示:

+---------+-------------------+-------------------+
| Form ID | Attachment ID - 1 | Attachment ID - 2 |
+---------+-------------------+-------------------+
| 1       | 1                 | 2                 |
| 2       | 3                 | NULL              |
| 3       | 4                 | NULL              |
| 4       | NULL              | NULL              |
| 5       | 5                 | 6                 |
| 6       | 7                 | NULL              |
+---------+-------------------+-------------------+

2 个答案:

答案 0 :(得分:2)

使用聚合和left join

SELECT f.id as `Form ID`,
       MIN(a.id) as `Attachment ID - 1` ,
       (CASE WHEN MIN(a.id) <> MAX(a.id) THEN MAX(a.id) END) as `Attachment ID - 2`
FROM   form f left join
       attachment a
       on f.id = a.form_id
GROUP BY f.id;

答案 1 :(得分:1)

试试这个:

SELECT FormID, 
       MAX(CASE WHEN AttachmentNo % 2 = 1 THEN AttachmentID ELSE 0 END) AS 'Attachment ID - 1', 
       MAX(CASE WHEN AttachmentNo % 2 = 0 THEN AttachmentID ELSE 0 END) AS 'Attachment ID - 2'
FROM (SELECT f.id AS FormID, a.id AS AttachmentID, 
             IF(@formId = @formId:=f.id, @id:=@id+1, @id:=1) AS AttachmentNo
      FROM form f 
      LEFT JOIN attachment ON f.id = a.form_id, (SELECT @formId:= 0, @id:=0) AS A 
      ORDER BY f.id. a.id
     ) AS A
GROUP BY FormID