If my table looks like this:
id | colA | colB | colC
===========================
1 | red | blue | yellow
2 | orange | red | red
3 | orange | blue | cyan
What SELECT query do I run such that the results returned are:
blue, cyan, orange, red, yellow
Basically, I want to extract a collective list of distinct values across multiple columns and return them in alphabetical order.
I am not concerned with performance optimization, because the results are being parsed to an XML file that will serve as a cache (database is hardly updated). So even a dirty solution would be fine.
Thanks for any help!
To select distinct values in two columns, you can use least() and greatest() function from MySQL.
Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order.
To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.
SELECT DISTINCT FIELD1, FIELD2, FIELD3 FROM TABLE1 works if the values of all three columns are unique in the table. If, for example, you have multiple identical values for first name, but the last name and other information in the selected columns is different, the record will be included in the result set.
(SELECT DISTINCT colA AS color FROM table) UNION
(SELECT DISTINCT colB AS color FROM table) UNION
(SELECT DISTINCT colC AS color FROM table)
ORDER BY color
Just do it the normal way:
create table new_tbl(col varchar(50));
insert into new_tbl(col)
select cola from tbl
union
select colb from tbl
union
select colc from tbl
Then sort:
select col from new_tbl order by col
Or if you don't want staging table, just do:
select cola as col from tbl
union
select colb from tbl
union
select colc from tbl
order by col
Note: UNION automatically remove all duplicates, if you want to include duplicates, change the UNION to UNION ALL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With