Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select distinct from multiple fields using sql

I have 5 columns corresponding to answers in a trivia game database - right, wrong1, wrong2, wrong3, wrong4

I want to return all possible answers without duplicates. I was hoping to accomplish this without using a temp table. Is it possible to use something similar to this?:

select c1, c2, count(*)
from t
group by c1, c2

But this returns 3 columns. I would like one column of distinct answers.

Thanks for your time

like image 692
Bryan Avatar asked Feb 13 '09 17:02

Bryan


People also ask

How can I get distinct values from multiple columns in SQL?

Select with distinct on all columns of the first query. Select with distinct on multiple columns and order by clause. Count() function and select with distinct on multiple columns.

How do I use distinct on all columns in SQL?

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.

Can we apply distinct on two columns?

Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.

Does distinct apply to all columns SQL Server?

Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.


Video Answer


1 Answers

This should give you all distinct values from the table. I presume you'd want to add where clauses to select only for a particular question. However, this solution requires 5 subqueries and can be slow if your table is huge.

SELECT DISTINCT(ans) FROM (
    SELECT right AS ans FROM answers
    UNION
    SELECT wrong1 AS ans FROM answers
    UNION
    SELECT wrong2 AS ans FROM answers
    UNION
    SELECT wrong3 AS ans FROM answers
    UNION
    SELECT wrong4 AS ans FROM answers
) AS Temp
like image 148
achinda99 Avatar answered Nov 20 '22 18:11

achinda99