【问题标题】:Combining two tables with a different column将两个表与不同的列组合在一起
【发布时间】:2012-01-26 07:44:07
【问题描述】:

我必须选择要使用 UNION 组合的请求:

Table 1 : Table_a, table_b 和 table_c 之间的连接

id_table_a   desc_table_a   table_b.id_user  table_c.field
-----------------------------------------------------------
1            desc1            1                 field1
2            desc2            2                 field2
3            desc3            3                 field3

表 2:这也是 Table_a、table_b 和 table_c 之间的连接,但它有以下列:

id_table_a   desc_table_a   table_c.id_user  table_c.field
-----------------------------------------------------------
4            desc4            4                 field4
5            desc5            5                 field8
9            desc9            6                 field9

两者的区别在于表1中我们有table_b.id_user和表二 table_c.id_user 代替。

组合表

  id_table_a   desc_table_a     id_user  table_c.field
    -----------------------------------------------------------
    1            desc1            1                 field1
    2            desc2            2                 field2
    3            desc3            3                 field3
    4            desc4            4                 field4
    5            desc5            5                 field5
    9            desc9            6                 field6

我已经有加入请求,但是在两者之间进行联合给了我

ORA-01790 expression must have same datatype as corresponding expression

这是有道理的,因为两列不一样。

我为此使用 zend_Db 的 join 和 union。

那么我该如何解决这个问题才能得到结果呢?

谢谢。

【问题讨论】:

  • 您使用的查询中所有字段的数据类型是什么?您的查询是什么?
  • 表1和表2字段的数据类型完全相同,table_b和table_c中的id_user在DB中的类型相同(NUM​​BER(6,0))
  • 好吧,ORA-01790 仅在它们不存在时才会发生(参见例如这里:techonthenet.com/oracle/errors/ora01790.php

标签: oracle zend-framework plsql union


【解决方案1】:

上面的结果和你表中的列顺序一样吗?因为 oracle 在列顺序上很严格。下面这个例子产生了一个错误:

create table test1_1790 (
col_a varchar2(30),
col_b number,
col_c date);

create table test2_1790 (
col_a varchar2(30),
col_c date,
col_b number);

select * from test1_1790
union all
select * from test2_1790;

ORA-01790:表达式必须与对应的表达式具有相同的数据类型

正如您所见,错误的根本原因在于使用 * 作为列列表说明符所暗示的列顺序不匹配。通过显式输入列列表可以轻松避免此类错误:

select col_a, col_b, col_c from test1_1790
union all
select col_a, col_b, col_c from test2_1790;

此错误更常见的情况是您无意中交换(或移动)了 SELECT 列表中的两个或更多列:

select col_a, col_b, col_c from test1_1790
union all
select col_a, col_c, col_b from test2_1790;

或者,如果上述方法不能解决您的问题,如何在列中创建一个 ALIAS 像这样:(查询和你的不一样,但这里的重点是如何在列中添加别名。)

SELECT id_table_a, 
       desc_table_a, 
       table_b.id_user as iUserID, 
       table_c.field as iField
UNION
SELECT id_table_a, 
       desc_table_a, 
       table_c.id_user as iUserID, 
       table_c.field as iField

希望这会有所帮助。

【讨论】:

  • 非常感谢,这两个建议都做了,效果很好:)
猜你喜欢
  • 2020-01-27
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-20
  • 2021-09-08
  • 2014-12-09
相关资源
最近更新 更多