Select different fields as one field (without concat)

I have a table with 2 fields, val1and val2that contain the same type. val1is mandatory, but val2optional, but if present, must be relevant val1.

CREATE TABLE VALS (
id INT NOT NULL AUTO_INCREMENT,
val1 INT NOT NULL,
val2 INT DEFAULT NULL,
timesign TIMESTAMP);

For this, I want to get all the values ​​coming from a field val1or val2, in one field res, so this

INSERT INTO VALS (val1, val2) VALUES
(1, null),
(2, null),
(3, 4),
(5, null),
(6, 7),
(8, null);

can be obtained in only one field:

+------+
| res  |
+------+
| 1    |
| 2    |
| 3    |
| 4    |
| 5    |
| 6    |
| 7    |
| 8    |
+------+

How to do it?

+4
source share
3 answers

Try the following:

SELECT val1 as res 
FROM VALS

UNION

SELECT val2 as res  
FROM VALS
WHERE val2 is notNULL;

You do not need a "distict", Union itself provides a set.

+4
source

One join request

SELECT a AS f FROM t
UNION 
SELECT b AS f FROM t HAVING f IS NOT NULL ORDER BY f

Works when both columns can be NULL

+3

:

select  resultcol from ( select distict val1 as resultcol from vals union select distinct val2 as resultcol from vals)alias order by resultcol

+1

Source: https://habr.com/ru/post/1537622/


All Articles