Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select different fields as one field (no CONCAT)

Tags:

sql

mysql

field

I have a table with 2 fields, val1 and val2, that contain same type. val1 is mandatory and val2 is optional -- but if present, should count as much as val1.

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

For that, I want to retrieve all values, whether coming from val1 or val2 field, into one field res, so that this

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

can be retrieved to one field only:

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

How to do this?

like image 420
Jago Avatar asked Feb 14 '23 03:02

Jago


1 Answers

Try this:

SELECT val1 as res 
FROM VALS

UNION

SELECT val2 as res  
FROM VALS
WHERE val2 is notNULL;

You don't need "distict", Union is itself give set.

like image 93
Grijesh Chauhan Avatar answered Feb 16 '23 10:02

Grijesh Chauhan