0

所以我有一张有 3 列的桌子:

Col1   Col2   Col3
 a       b     c
 b       c    null
 a      null   b
 c       d     a

我想要的输出将是:

a,b,c,d,null

如果可能的话,我希望将输出放在一个字符串中。

我试过了:

SELECT DISTINCT col1, col2, col3 FROM table

并没有得到想要的结果。有任何想法吗?

4

4 回答 4

2

单字符串解决方案(参见sqlfiddle):

SELECT  GROUP_CONCAT(COALESCE(c, 'NULL'), ',')
FROM    (
        SELECT  col1 c
        FROM    mytable
        UNION
        SELECT  col2 c
        FROM    mytable
        UNION
        SELECT  col3 c
        FROM    mytable
        ) q
于 2013-01-17T22:10:19.860 回答
1

这在sqlite中有效吗:

select col1 from table 
union
select col2 from table
union 
select coll3 from table

或者:

select col1 from table where col1 is not null
union
select col2 from table where col2 is not null
union 
select coll3 from table where col3 is not null

消除空值。

请注意,我认为这不会很快执行,但我知道在 mssql union 中会对结果做不同的处理

于 2013-01-17T22:02:59.473 回答
1
SELECT Col1
FROM table
UNION
SELECT Col2
FROM table
UNION
SELECT Col3
FROM table
于 2013-01-17T22:04:30.117 回答
0

如果您使用的是 MySql,则可以使用此解决方案:

select group_concat(coalesce(c,'null') order by c is null, c)
from (
  select col1 c from tbl
  union
  select col2 c from tbl
  union
  select col3 c from tbl
) u

联合查询选择所有值,删除所有重复项。然后我以单个字符串返回结果,按值排序,最后为 null 值,并将 null 转换为“null”(因为 group_concat 将忽略 null 值)。

如果你使用 SQLite,Group_Concat 不支持 order by,你可以使用这个:

select group_concat(coalesce(c,'null'))
from (
  select col1 c, col1 is null o from mytable
  union
  select col2 c, col2 is null o from mytable
  union
  select col3 c, col3 is null o from mytable
  order by o, c
) u
于 2013-01-17T22:09:23.073 回答