UNION SELECT不显示所有列

时间:2014-07-03 18:02:12

标签: mysql sql join view union

我有几个VIEW个嵌套到用作报告的较大VIEW

CREATE VIEW view1 AS
    SELECT table1.col1 AS t1c1, table1.col2 AS t1c2
    FROM table1
    WHERE table1.col1 = 0
;

SAMPLE OUTPUT:

SELECT * FROM view1;
+-------------------+
|  t1c1  |   t1c2   |
+--------+----------+
|    0   |  t1stuff |
+--------+----------+
|    0   | t1stuff2 |
+--------+----------+

CREATE VIEW view2 AS
    SELECT table2.col1 AS t2c1, table2.col2 AS t2c2
    FROM table2
    WHERE table2.col1 = 5
;

SAMPLE OUTPUT:

SELECT * FROM view2;
+-------------------+
|  t2c1  |   t2c2   |
+--------+----------+
|    5   |  t2stuff |
+--------+----------+
|    5   | t2stuff2 |
+--------+----------+

然后我将它们组合成一个“报告”视图,如下所示:

CREATE VIEW view3 AS
    SELECT * FROM view1
    UNION
    SELECT * FROM view2
;

SAMPLE OUTPUT:
SELECT * FROM view3;
+-------------------+
|  t1c1  |   t1c2   |
+--------+----------+
|    0   |  t1stuff |
+--------+----------+
|    0   | t1stuff2 |
+--------+----------+
|    5   |  t2stuff |
+--------+----------+
|    5   | t2stuff2 |
+--------+----------+

预期的INSTEAD:

+-------------------+--------+----------+
|  t1c1  |   t1c2   |  t2c1  |   t2c2   |
+--------+----------+--------+----------+
|    0   |  t1stuff |        |          |
+--------+----------+--------+----------+
|    0   | t1stuff2 |        |          |
+--------+----------+--------+----------+
|        |          |   5    | t2stuff  |
+--------+----------+--------+----------+
|        |          |   5    | t2stuff2 |
+--------+----------+--------+----------+

如何达到预期效果?

2 个答案:

答案 0 :(得分:5)

有人会质疑为什么你在单个查询中这样做,如果没有数据是相关的,甚至不共享列。但无论如何,您必须指定所有列:

select col1 as t1c1, col2 as t1c2, null as t2c1, null as t2c2
from view1
union all
select null as t1c1, null as t1c2, col1 as t2c1, col2 as t2c2
from view2

答案 1 :(得分:0)

SELECT * FROM view1
FULL OUTER JOIN view2
  on 1=0

在这种情况下,联盟用于加入类似数据,您不希望数据位于同一列中 这里的联接似乎更合适......

Full out返回每组中的所有记录,因为我们不希望任何匹配,我们可以使用1 = 0,这样他们就没有关联,但是你得到了预期的结果。

bah ... mySQL不支持完全外连接...所以需要联合。再次被非ancii标准引擎烧毁。