Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将MySQL行转换为5列_Mysql_Sql_String_Pivot_Window Functions - Fatal编程技术网

如何将MySQL行转换为5列

如何将MySQL行转换为5列,mysql,sql,string,pivot,window-functions,Mysql,Sql,String,Pivot,Window Functions,我是MySQL新手。我有一个数据表,我想把它转换成5行 从选择tbl\U文件中的文件。我有 +--------+ | File | +--------+ | B.jpg | +--------+ | X.jpg | +--------+ | H.png | +--------+ | C.png | +--------+ | A.gif | +--------+ | G.pdf | +--------+ | Y.docx | +--------+ | U.jpeg

我是MySQL新手。我有一个数据表,我想把它转换成5行

选择tbl\U文件中的文件
。我有

+--------+
| File   |  
+--------+
| B.jpg  | 
+--------+
| X.jpg  | 
+--------+
| H.png  | 
+--------+
| C.png  | 
+--------+
| A.gif  |
+--------+
| G.pdf  | 
+--------+
| Y.docx | 
+--------+
| U.jpeg | 
+--------+
当行旋转到5列时,我需要这样做

+-------+--------+--------+-------+-------+
| A     | B      | C      | D     | E     |
+-------+--------+--------+-------+-------+
| B.jpg | X.jpg  | H.png  | C.png | A.gif |
+-------+--------+--------+-------+-------+
| G.pdf | Y.docx | U.jpeg |       |       |
+-------+--------+--------+-------+-------+
当第一行填充到其限制值5时,下一行继续填充

这就是我尝试过的:

按id从tbl_文件组中选择组_CONCAT(文件)
我没有得到我想要的


非常感谢。

有点难看。。。但这是可能的。您可以使用窗口函数,但您需要一个列来定义行的顺序,我假设
id

select
        max(case when rn % 5 = 0 then file end) as filea,
        max(case when rn % 5 = 1 then file end) as fileb,
        max(case when rn % 5 = 2 then file end) as filec,
        max(case when rn % 5 = 3 then file end) as filed,
        max(case when rn % 5 = 4 then file end) as filee
from (
    select t.*, row_number() over(order by id) - 1 rn
    from mytable t
) t
group by floor(rn / 5)

filea | fileb | filec | filed | filee :---- | :----- | :----- | :---- | :---- B.jpg | X.jpg | H.png | C.png | A.gif G.pdf | Y.docx | U.jpeg | null | null 文件A |文件B |文件C |文件|文件E :---- | :----- | :----- | :---- | :---- B.jpg | X.jpg | H.png | C.png | A.gif G.pdf | Y.docx | U.jpeg | null | null
只需处理应用程序中的显示逻辑即可code@strawberry我的应用程序代码中已经有很多循环。加上这个会使速度变慢。由于DB更快,我考虑直接运行它并返回一个表。