如何将一行的列转换为一行?
表中数据如下:
+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
| a1 | a2 | a3 | a4 |
+------+------+------+------+
所需的输出:该行中的所有值都应该放在如下的单列中。
+---------------+
| All_cols |
+---------------+
| a1,a2,a3,a4 |
+---------------+
如图所示:这里mytable
总是有一个记录,所以我需要如下输出。
想要避免低于 sql,因为它需要多个连接:
select a1.name from accounts a1 where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'
union
Select a2.name from accounts a1
left join accounts a2 on a1.id=a2.parent_id where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'
union
Select a3.name from accounts a1
left join accounts a2 on a1.id=a2.parent_id
left join accounts a3 on a2.id=a3.parent_id where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'
union
Select a4.name from accounts a1
left join accounts a2 on a1.id=a2.parent_id
left join accounts a3 on a2.id=a3.parent_id
left join accounts a4 on a3.id=a4.parent_id where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'
union
Select a5.name from accounts a1
left join accounts a2 on a1.id=a2.parent_id
left join accounts a3 on a2.id=a3.parent_id
left join accounts a4 on a3.id=a4.parent_id
left join accounts a5 on a4.id=a5.parent_id where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'