Somya Arora Somya Arora - 5 months ago 11
MySQL Question

how to select distinct values from rows and columns both together

This is my database table.

This is my database table with some values.There are different topic names from topic1 to topic8.
And I want to access the distinct topic names from all these values.
What will be the sql query for it ?

Answer

Use a union query:

select topic1 as topic from t union
select topic2 as topic from t union
select topic3 as topic from t union
select topic4 as topic from t union
select topic5 as topic from t union
select topic6 as topic from t union
select topic7 as topic from t union
select topic8 as topic from t;

If you don't want NULL, then include a WHERE clause:

select topic1 as topic from t where topic1 is not null union
select topic2 as topic from t where topic2 is not null union
select topic3 as topic from t where topic3 is not null union
select topic4 as topic from t where topic4 is not null union
select topic5 as topic from t where topic5 is not null union
select topic6 as topic from t where topic6 is not null union
select topic7 as topic from t where topic7 is not null union
select topic8 as topic from t where topic8 is not null;