【问题标题】:ORA-00904 Invalid identifier and column ambiguityORA-00904无效的标识符和列歧义
【发布时间】:2014-01-20 00:13:21
【问题描述】:

我正在尝试运行以下 sql 查询:

select customers.cust_first_name, customers.cust_last_name, customers.cust_gender,
customers.cust_city, countries.country_name, products.prod_id
from customers
join countries on customers.cust_id = countries.country_id
join products on profits.prod_id = products.prod_id
join profits on customers.cust_id = profits.cust_id

但我收到以下错误:

An error was encountered performing the requested operation:

ORA-00904: "PROFITS"."PROD_ID":Invalid identifier 
00904.00000-"%s: invalid Identifier" 

我使用的是 oracle 11g 版本。

您能否指导我如何动态解决/处理列歧义问题,即是否有办法让数据库忽略列歧义问题?

【问题讨论】:

    标签: sql oracle oracle11g


    【解决方案1】:

    您必须在from 子句中命名表,然后才能在on 语句中使用它:

    select customers.cust_first_name, customers.cust_last_name, customers.cust_gender,
           customers.cust_city, countries.country_name, products.prod_id
    from customers join
         countries
         on customers.cust_id = countries.country_id join
         profits
         on customers.cust_id = profits.cust_id join
         products
         on profits.prod_id = products.prod_id;
    

    如果您使用表别名,您的查询也会更具可读性:

    select cu.cust_first_name, cu.cust_last_name, cu.cust_gender,
           cu.cust_city, co.country_name, pr.prod_id
    from customers cu join
         countries co
         on cu.cust_id = co.country_id join
         profits pf
         on cu.cust_id = pf.cust_id join
         products pr
         on pf.prod_id = pr.prod_id;
    

    【讨论】:

    • 感谢您的帮助。您能否也清除我的疑问,即数据库无法忽略列歧义问题,除非在查询中明确提及。换句话说,我们可以避免在查询中为重复列添加前缀吗?
    • @kashif4u 。 . .我认为向列添加表前缀是个好主意。如果列名是唯一的,则不需要它们——因为它似乎在大多数列的表中,因为列名以表前缀开头。如果您使用natural joinusing 子句,那么您可以根据标准引用不带前缀的连接列(虽然我不确定Oracle 是否支持这一点)。
    • 嗨,戈登,我还有一个问题要问你。根据您的建议,我尝试查看在线文献,但找不到关于多个连接的文档。
    • 这个查询给了我同样的麻烦。谢谢 select PROFITS.QUANTITY_SOLD, PROFITS.UNIT_COST, PRODUCTS.PROD_NAME, PRODUCTS.PROD_DESC, COUNTRIES.COUNTRY_NAME, COUNTRIES.COUNTRY_REGION 从 COUNTRIES 加入 CUSTOMERS 在 COUNTRIES.COUNTRY_ID = CUSTOMERS.COUNTRY_ID 加入 PROFITS on PRODUCTS.CUST_ID = PROFITS.CUST_ID 加入 CUSTOMERS PROFITS.CUST_ID = CUSTOMERS.CUST_ID。
    • @kashif4u 。 . .它也有同样的问题。阅读我的回答,了解有效查询和无效查询之间的区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2022-01-22
    • 2019-06-29
    相关资源
    最近更新 更多