引用两个表中的列别名

Referring to a column alias in two tables

我有两个配置单元 SQL 表,其中包含以下列。

table_1

|customer_id | ip_address|

region_table

|country_name | region_name|

我试过了,

SELECT table_1.customer_id, table_1.ip_address, getCountry(ip_address) AS Country, region_table.region_name FROM table_1 JOIN region_table ON region_table.country_name = Country;

getCountry() is UDF which returns the country name when the IP address is passed into it. I want to use that country name to create another column with the corresponding region from the region_table. And i want to get the following table as my output.

customer_id | ip_address | Country | region_name

关于我在查询中遗漏的内容有什么想法吗?

select      c.customer_id
           ,c.ip_address
           ,getCountry(c.ip_address) as Country
           ,r.region_name 

from                table_1         c

            join    region_table    r

            on      r.country_name = 
                    getCountry(c.ip_address)

对于 Oracle,您不能在同一查询的 WHERE 子句中引用 SELECT 语句中定义的列别名!!因为数据库引擎首先评估 WHERE 子句并识别符合条件的行,然后继续获取查询的 SELECT 部分中定义的列。

在你的情况下,正确的查询应该是

select 
  table_1.customer_id, 
  table_1.ip_address, 
  getCountry(ip_address) AS Country, 
  region_table.region_name 
FROM table_1 
JOIN region_table ON region_table.country_name = getCountry(table_1 .ip_address);