Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to address multiple columns as one in MySQL?

Tags:

sql

select

mysql

Columns a, b and c contain some values of the same nature. I need to select all the unique values. If I had just one column I'd use something like

SELECT DISTINCT a FROM mytable ORDER BY a;

but I need to treat a, b and c columns as one and gett all the unique values ever occurring among them.

As an example, let this be a CSV representation of mytable, the first row naming the columns:

a, b, c
1, 2, 3
1, 3, 4
5, 7, 1

The result of the query is to be:

1
2
3
4
5
7

UPDATE: I don't understand why do all of you suggest wrapping it in an extra SELECT? It seems to me that the answer is

(SELECT `a` AS `result` FROM `mytable`)
UNION (SELECT `b` FROM `mytable`)
UNION (SELECT `c` FROM `mytable`)
ORDER BY `result`;

isn't it?

like image 207
Ivan Avatar asked Dec 05 '22 18:12

Ivan


1 Answers

So you want one column all with unique values from a, b and c? Try this:

(select a as yourField from d1)
union
(select b from d2)
union
(select c from d3)
order by yourField desc
limit 5

Working example

Edited after requirements changed... There you have the order by and limit you requested. Of course, you'll get only 5 records in this example

like image 160
Mosty Mostacho Avatar answered Dec 08 '22 02:12

Mosty Mostacho