如果您知道最大数量为 12,这是实现此目的的一种方法。它使用MAX
和CASE
,获取每个附件的行号。
SELECT
I.Id issue_id,
I.title,
MAX(CASE WHEN d.row_number = 1 THEN D.attachment END) attachment1,
MAX(CASE WHEN d.row_number = 2 THEN D.attachment END) attachment2,
MAX(CASE WHEN d.row_number = 3 THEN D.attachment END) attachment3,
MAX(CASE WHEN d.row_number = 4 THEN D.attachment END) attachment4,
MAX(CASE WHEN d.row_number = 5 THEN D.attachment END) attachment5,
MAX(CASE WHEN d.row_number = 6 THEN D.attachment END) attachment6,
MAX(CASE WHEN d.row_number = 7 THEN D.attachment END) attachment7,
MAX(CASE WHEN d.row_number = 8 THEN D.attachment END) attachment8,
MAX(CASE WHEN d.row_number = 9 THEN D.attachment END) attachment9,
MAX(CASE WHEN d.row_number = 10 THEN D.attachment END) attachment10,
MAX(CASE WHEN d.row_number = 11 THEN D.attachment END) attachment11,
MAX(CASE WHEN d.row_number = 12 THEN D.attachment END) attachment12
FROM Issues I
LEFT JOIN (
SELECT
a.issue_id,
@running:=if(@previous=a.issue_id,@running,0) + 1 as row_number,
@previous:=a.issue_id,
a.attachment
FROM Attachments a
JOIN (SELECT @previous := 0) r
ORDER BY a.issue_id, a.attachment
) D ON I.ID = D.issue_id
GROUP BY I.Id, I.Title
这是SQL Fiddle。
我必须进行编辑以使每个组的行号重置。现在应该可以上班了。另外,根据@spencer7593 的精彩评论,我稍微更新了查询。
- 编辑 -
为了回应OP关于需要动态结果的评论,这应该有效:
设置@sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(d.row_number = ', d.row_number, ',D.attachment,NULL)) AS attachment', d.row_number)
) INTO @sql
FROM Issues I
LEFT JOIN (
SELECT
a.issue_id,
@running:=if(@previous=a.issue_id,@running,0) + 1 as row_number,
@previous:=a.issue_id,
a.attachment
FROM Attachments a
JOIN (SELECT @previous := 0) r
ORDER BY a.issue_id, a.attachment
) D ON I.ID = D.issue_id
;
SET @sql = CONCAT('SELECT I.Id issue_id,
I.title, ', @sql, '
FROM Issues I
LEFT JOIN (
SELECT
a.issue_id,
@running:=if(@previous=a.issue_id,@running,0) + 1 as row_number,
@previous:=a.issue_id,
a.attachment
FROM Attachments a
JOIN (SELECT @previous := 0) r
ORDER BY a.issue_id, a.attachment
) D ON I.ID = D.issue_id
GROUP BY I.Id, I.Title');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
这是SQL Fiddle。