我有一个表,它只是三个不同列中的数字。我正在检查每一行的总和,并根据总值输出一个字符串,查询的结构如下:
select statement one as string1
union all
select statement two as string2
and so on...
我遇到的问题是,我希望输出按原始顺序逐行排列,所以它会像:
string1
string3
string1
string2 and so on
我得到的是:
string1
string1
string1
string1
string2
string2
and so on...
如何解决?
在MySQL 8.0中,您可以使用row_number
函数生成一个要排序的连续数字。此外,您还可以添加一个硬编码值来区分值来自的列,然后对它们进行排序:
SELECT col1 AS col, ROW_NUMBER() OVER (ORDER BY col1) AS rn, 1 AS ind FROM mytable
UNION ALL
SELECT col2 AS col, ROW_NUMBER() OVER (ORDER BY col1) AS rn, 2 AS ind FROM mytable
ORDER BY rn, ind
DBFiddle样本