如何将一行的列转换为一行?
将数据放在表格中如下:
+------+------+------+------+
| 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'
答案 0 :(得分:0)
你可以在四个单一的电话上发出UNION
SELECT col1 FROM mytable
UNION
SELECT col2 FROM mytable
UNION
SELECT col3 FROM mytable
UNION
SELECT col4 FROM mytable
将输出
你说那个
mytable总是有一条记录。
请注意,如果您有多条记录,最好在上面的每个WHERE
语句中使用相同的SELECT
条件。