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

MySQL Retrieve Rows and Convert them to Columns

我正在使用以下查询 return 表单 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              |
+---------+-------------------+-------------------+

使用聚合和 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;

试试这个:

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