0

This question already has an answer here:

For starters: yes, I've seen there are lots of questions on combining two/multiple columns - but so far I neither found the answer to my question nor something to get me started trying further (which I did).


I have: a table consisting of two INT fields.
I want: a single column holding the distinct values of both fields.

Examle table:

| a | b |
|---|---|
| 1 | 2 |
| 1 | 3 |
| 1 | 7 |
| 2 | 3 |
| 3 | 5 |
| 5 | 7 |

My desired result would in that case be:

| 1 |
| 2 |
| 3 |
| 5 |
| 7 |

Can this be done with a single query? What would that look like?

// EDIT: some side info (which I think is irrelevant, however, I don't want to hide it):
b is always greater than a.

marked as duplicate by ypercubeᵀᴹ, Andriy M, RLF, RolandoMySQLDBA mysql Jun 21 '16 at 18:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4
SELECT a AS result
FROM tableX

UNION DISTINCT

SELECT b 
FROM tableX ;
  • Thanks. That was fast. Does this mean there is no solution with only a single SELECT? It's only a single query, yes. I should've written SELECT in my question, though. :) – tfrommen Jun 21 '16 at 10:55
  • I don't see why one would want this weird requirement (a single SELECT keyword in the query). But no, I don't think that is possible. – ypercubeᵀᴹ Jun 21 '16 at 10:57
  • UNION DISTINCT gives an incorrect result. Just UNION seems correct. Any idea on this? – tfrommen Jun 21 '16 at 11:04
  • UNION and UNION DISTINCT should give you the same exact result. What result did you get? – ypercubeᵀᴹ Jun 21 '16 at 11:12
  • 1
    @tfrommen: Just to confirm that this should work in MySQL: sqlfiddle.com/#!9/8971ab/1 – Andriy M Jun 21 '16 at 16:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.