我有一个包含2个字段的表val1
和val2
,其中包含相同的类型。 val1
是强制性的,val2
是可选的 - 但如果存在,则应计入val1
。
CREATE TABLE VALS (
id INT NOT NULL AUTO_INCREMENT,
val1 INT NOT NULL,
val2 INT DEFAULT NULL,
timesign TIMESTAMP);
为此,我想将所有值(无论是来自val1
还是val2
字段)检索到一个字段res
,以便
INSERT INTO VALS (val1, val2) VALUES
(1, null),
(2, null),
(3, 4),
(5, null),
(6, 7),
(8, null);
只能检索到一个字段:
+------+
| res |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
+------+
怎么做?
答案 0 :(得分:4)
试试这个:
SELECT val1 as res
FROM VALS
UNION
SELECT val2 as res
FROM VALS
WHERE val2 is notNULL;
你不需要“分心”,联盟本身就是一套。
答案 1 :(得分:3)
一个带联合的查询
SELECT a AS f FROM t
UNION
SELECT b AS f FROM t HAVING f IS NOT NULL ORDER BY f
当两列都可以NULL
答案 2 :(得分:1)
试试这个:
select resultcol from ( select distict val1 as resultcol from vals union select distinct val2 as resultcol from vals)alias order by resultcol
Union删除所有重复值