Pergunta

I have tried several methods to select multiple columns in a table for unique or distinct data from a table, including queries like:

SELECT
(SELECT GROUP_CONCAT(DISTINCT a) FROM TableName),
(SELECT GROUP_CONCAT(DISTINCT b) FROM TableName),
(SELECT GROUP_CONCAT(DISTINCT c) FROM TableName);

SELECT(a, b, c) FROM TableNamegroup by 'a' order by a asc;

SELECT DISTINCT a FROM TableName
UNION
SELECT DISTINCT b FROM TableName
UNION
SELECT DISTINCT c FROM TableName;

But they either don't work or return the information in a format that I can't use. What I need is a format like this:

+--------------------+
| a    | b    | c    |
|--------------------|
| 1    | 1    | 1    |
| 2    | 2    | 2    |
| 3    | 3    | 3    |
   etc......

Short of doing individual queries, is there a way to do this?

Foi útil?

Solução

If you need three columns, then your select needs three columns. If you want unique combinations:

select distinct a, b, c
from TableName;

Is this what you want?

I suspect that you want lists of the unique ids in three columns. You can do this using variables in MySQL:

select rn, max(a) as a, max(b) as b, max(c) as c
from ((select @rna := @rna + 1 as rn, a, null as b, null as c
       from (select distinct a from TableName) t cross join
            (select @rna := 0) const
      ) union all
      (select @rnb := @rnb + 1 as rn, null, b, null
       from (select distinct b from TableName) t cross join
            (select @rnb := 0) const
      ) union all
      (select @rnc := @rnc + 1 as rn, null, null, c
       from (select distinct c from TableName) t cross join
            (select @rnc := 0) const
       group by c
      )
     ) abc
group by rn
order by rn;

Here is an example of it working in SQL Fiddle.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top