从所有列中选择不同的值

时间:2016-07-23 15:39:06

标签: php mysql

我想从每列中仅选择不同的值。不明显的组合。 这是我的查询,但它返回所有列的不同组合。我希望每列显示自己独特的值而不依赖于其他列。

 $sql= "select distinct
            CASE WHEN col1 not regexp '[0-9]' THEN col1 else null end as col1
            ,CASE WHEN col2 not regexp '[0-9]' THEN col2 else null end as col2
            ,CASE WHEN col3 not regexp '[0-9]' THEN col3 else null end as col3 from table_name";

它返回:

col1| col2| col3
a      1     3
b      2     4
c      2     4
d      1     3

你们可以看到col2和col3的值不是很明显我只希望与col2和col3不同。谢谢!

1 个答案:

答案 0 :(得分:0)

我最好猜测你想要的是使用union all

select distinct (case when col1 not regexp '[0-9]' then col1 end) as col1, 'col1' as which
from table_name
union all
select distinct (case when col2 not regexp '[0-9]' then col2 end) as col2, 'col2' as which
from table_name
union all
select distinct (case when col3 not regexp '[0-9]' then col3 end) as col3, 'col3' as which
from table_name;

这会生成一个包含两列的结果,一列是列名,另一列是列中的不同值。