select语句出错,其中union all在子查询中

时间:2014-03-05 16:02:09

标签: sql oracle11g

在Oracle 11g中,我遇到了一个查询错误,无法解释为什么它对我有误。这是查询:

select
  main_data.issue_number,
  main_data.transaction_number
 from
 (
    select
      p1.payment_date,
      p1.media_number,
      p1.payment_amount,
      p1.issue_number, 
      p1.advice_na_number,
      name.name_address_line_1,
      name.name_address_line_2,
      name.name_address_line_3,
      name.name_address_line_4,
      name.name_address_line_5,
      name.name_address_line_6,
      name.name_address_line_7,
      name.name_address_city, 
      name.state_code,
      name.address_country_code, 
      name.zip_code, 
      name.tax_id_number,
      p1.output_tx_number_prin,
      p1.output_tx_number_int,
      '' as "transaction_number",
      p1header.check_account_number

    from 
    p1
    left join name on p1.name_address_number = name.name_address_number
    left join p1header on p1.issue_number = p1header.issue_number

  UNION ALL

  select 
      check.date_of_payment,
      check.media_number, 
      check.payment_amount,
      check.issue_number,
      check.payee_na_number,
      name.name_address_line_1,
      name.name_address_line_2,
      name.name_address_line_3,
      name.name_address_line_4,
      name.name_address_line_5,
      name.name_address_line_6,
      name.name_address_line_7,
      name.name_address_city, 
      name.state_code,
      name.address_country_code, 
      name.zip_code, 
      name.tax_id_number,
      '' as "output_tx_number_prin",
      '' as "output_tx_number_int",
      check.transaction_number,
      check.dda_number as "check_account_number"
  from check
  left join name on check.payee_na_number = name.name_address_number
) main_data

选择上面的单个字段会给我一个“无效的标识符错误”。如果我select *那么它会让我回复数据而不会出现任何错误。我在这做错了什么?谢谢。

1 个答案:

答案 0 :(得分:1)

旧的引用标识符问题...请参阅database object naming documentation中的第9点,并注意Oracle建议不要使用带引号的标识符。

您已将列别名作为小写放在双引号内。这意味着任何对它的引用也必须引用并与案例完全匹配。所以这会奏效:

select
  main_data.issue_number,
  main_data."transaction_number"
from
...

但除非你急需拥有这样的别名 - 我怀疑你这样做,因为实际表列中的所有标识符名称都没有引用 - 从内部选择中删除双引号会更简单:

select
  main_data.issue_number,
  main_data.transaction_number
 from
 (
    select
  ...
      '' as transaction_number,
      p1header.check_account_number
  ...
  UNION ALL
  select 
    ...
      '' as output_tx_number_prin,
      '' as output_tx_number_int,
      check.transaction_number,
      check.dda_number as check_account_number
    ...

您实际上并不需要来对联合的第二个分支中的列进行别名;列标识符都将从第一个分支中获取。