简体   繁体   English

MySql 如何合并一列中的两列,使第二列输出在多行中位于第一列

[英]MySql How to Merge two columns in one column Such that second column ouput goes uder first column in multiple rows

How to Merge two columns in one column Such that second column ouput goes uder first column in multiple rows without using UNION in single query.如何合并一列中的两列这样第二列输出会在多行中的第一列下进行,而无需在单个查询中使用 UNION。

for Eg:例如:

column1 column2 
1          3
2          4

expected OP:预期操作:

 column1 
      1
      2
      3
      4

without using UNION in single query在单个查询中不使用 UNION

SELECT DISTINCT CASE WHEN t00.id = t01.id
                     THEN t1.column1
                     ELSE t2.column2 
                     END all_values
FROM       ( SELECT column1 id 
             FROM test
             ORDER BY 1
             LIMIT 2 ) t00
CROSS JOIN ( SELECT MIN(column1) id
             FROM test ) t01
CROSS JOIN test t1
CROSS JOIN test t2
ORDER BY 1

fiddle 小提琴

The table must have at least 2 rows.该表必须至少有 2 行。

Applicable for 5.x MySQL version.适用于 5.x MySQL 版本。

union all is the right approach: union all是正确的方法:

select column1 as col
from t
union all
select column2 
from t
order by col;

You can also use a cross join with the union all in a subquery:您还可以在子查询中使用带有union allcross join

select (case when seqnum = 1 then column1 else column2 end) as col
from t cross join
     (select row_number() over () as seqnum
      from t
      limit 2
     ) tt
order by col;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 mysql:搜索两列:第一列,然后第二列 - mysql : search two columns : one column first then second column Mysql合并表中的2列,但更喜欢第一列的值 - Mysql Merge 2 Columns in table but prefer first column value over second SQL 如何将多列折叠成两列,一列用于列标题,第二列用于列值 - SQL how to collapse multiple columns into two columns, one for column heading and the second for column value 将多行合并为一列 - Merge multiple rows into one column 如何更新一个表的两列,其中第二列将用第一列的值更新? - How to update two columns of one table in which second column will be updated with the value of first column? 导入两列,然后根据不同的分隔符和第一列将第二列分为许多列和行 - Importing two columns and dividing the second column into many columns and rows based on a different delimiter and based on the first column 合并两个MySQL结果列,其中一个列或另一个列不为null - Merge two MySQL results columns where one column or the other will be not null 如何将两个MySQL列合并为一列? - How to combine two MySQL columns to one column? 如果一列中有一个相同的值,如何合并两行并更改列名 - How to merge two rows in one if there is one same value in a column and change columns name MySQL通过查询将两个日期列合并为一列 - MySql merge two date columns to one column by query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM