Chrisvdberge
Chrisvdberge

Reputation: 1956

MySQL Select distinct values from 2 columns

I have a table wich has links in it. So amongst others, there are 2 columns that contain URLs; Source and Destination. I need to get a list of all the unique urls that are present in the table (to create a lookup table), but a url can be in both columns of course. Using distinct on the 2 columns seems to return unique combinations, rather than single values. Can I do this in 1 query or should I use 2 (one for each column) and then a 3d distinct select on that result?

Upvotes: 2

Views: 5513

Answers (2)

Mirco Ellmann
Mirco Ellmann

Reputation: 968

Try the following:

SELECT DISTINCT url
FROM (
    SELECT col1 AS url
    FROM TABLE
    UNION
    SELECT col2 AS url
    FROM TABLE
) urls

Upvotes: 2

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

You can use an UNION, which will remove the duplicates (while UNION ALL will keep the duplicates)

SELECT FirstUrlColumn AS url
FROM myTable
UNION
SELECT secondUrlColumn AS url
FROM myTable

Upvotes: 5

Related Questions