首批通过分布式安全可靠测评,为关键业务系统打造
OceanBase 使用 UNION ALL 的注意事项
更新时间:2026-05-21 09:16
本文讲述 OceanBase 数据库 MySQL 和 Oracle 模式下使用 UNION ALL 拼接 SQL 的注意事项。
适用版本
OceanBase 数据库 V2.x 和 V3.x 版本。
操作步骤
OceanBase 数据库 MySQL 模式下,UNION ALL 拼接 SQL 的前后字段类型要求必须一致,否则数据库本身为了兼容所有类型,会默认选择 VARCHAR,这样会让优化器对含有 UNION ALL 的 SQL 语句优化效果大打折扣。
以下为示例:两个视图 test_view1、test_view2,强烈建议不使用视图 test_view2。
obclient [(none)]> use db_mysql
Database changed
obclient [db_mysql]> create table test1(id int ,utime timestamp,primary key (id));
Query OK, 0 rows affected (0.716 sec)
obclient [db_mysql]> create table test2(id int ,utime timestamp,primary key (id));
Query OK, 0 rows affected (0.492 sec)
obclient [db_mysql]> create view test_view1 as select id,utime from test1 union all select id,utime from test2;
Query OK, 0 rows affected (0.114 sec)
obclient [db_mysql]> create view test_view2 as select id,utime from test1 union all select utime,id from test2;
Query OK, 0 rows affected (0.184 sec)
obclient [db_mysql]> desc test_view1;
+-------+-----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| utime | timestamp | YES | | NULL | |
+-------+-----------+------+-----+---------+-------+
2 rows in set (0.184 sec)
obclient [db_mysql]> desc test_view2;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | varchar(19) | NO | | NULL | |
| utime | varchar(19) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.072 sec)
如果是 Oracle 模式,则直接报错,不允许创建 UNION ALL 前后 SQL 数据类型不一致的视图。示例如下:直接报错 ORA-01790。
obclient [sys]> create view test_view2 as select id,utime from test1 union all select utime,id from test2;
ORA-01790: expression must have same datatype as corresponding expression