Skip to content
Advertisement

MySQL – select distinct value from two column

I have a table with the following structure:

How could I make a select statement on this table, which will return some rows of this table, where in each row, a specific id appears only one, indifferent on which column it is specified?

For the above result set, I would like a query that would return:

To give another example, if you would omit the first row in the original dataset:

the result set should be:

Advertisement

Answer

That’s actually an interesting problem. If I follow you correctly, you want to iterate through the dataset and only retain rows where both values were never seen before. You could use a recursive query:

The first CTE enumerates the rows ordered by both columns. Then the recursive query walks the resultset, checks if both values are new, and sets a flag accordingly of the columns. Flagged numbers are retained to be used for filtering in the following iteration.

Demo on DB Fiddle

Note that, given your requirement, not all values may appear in the resultset. Consider the following dataset:

Your logic will only return the first row.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement