Search code examples
mysqlechouniquemultiple-columns

MYSQL Echo Value only once from multible columns


I would like print out a list of names, each name only once. The Problem: I have two different columns with names in them, yet I want to display each name only once, not depending on the column. I am going to echo the result with PHP, so also loop's or other PHP actions are possible if there is no MYSQL only solution.

To visualise an example: (I also have an ID column as shown below)

ID     |Name1  |  Name2
-------|-------|-------
01     |  A    |   B
02     |  A    |   C
03     |  B    |   A

As seen above there are the same names in both columns, yet I want to get each name only once.

Locking like this (for example):

(List:)
A
B
C

Solution

  • something like this should do it:

    select distinct name
    from (
        select Name1 name from table_name
        union all
        select Name2 name from table_name
    )