我的表包含如下所示的值:
Column1 | Column2 | Column3 | Column4
=====================================
1 | 3 | 5 | NULL
1 | 3 | NULL | NULL
1 | 4 | NULL | NULL
2 | NULL | NULL | NULL
如果我希望结果只有唯一值而不是null,则查询如何如下所示:
1,2,3,4,5
答案 0 :(得分:1)
只需要4个查询,一个针对每个列进行选择,并将结果联合起来: -
SELECT Column1 AS aCol FROM SomeTable WHERE Column1 IS NOT NULL
UNION
SELECT Column2 AS aCol FROM SomeTable WHERE Column2 IS NOT NULL
UNION
SELECT Column3 AS aCol FROM SomeTable WHERE Column3 IS NOT NULL
UNION
SELECT Column4 AS aCol FROM SomeTable WHERE Column4 IS NOT NULL
或者,如果你只想要一个单独的字段返回它们全部是一致的: -
SELECT GROUP_CONCAT(aCol)
FROM
(
SELECT Column1 AS aCol FROM SomeTable
UNION
SELECT Column2 AS aCol FROM SomeTable
UNION
SELECT Column3 AS aCol FROM SomeTable
UNION
SELECT Column4 AS aCol FROM SomeTable
) Sub0