为什么从列别名查询时会出错?

Why do I get an error querying from column alias?

我从列别名查询时出错,不明白为什么。在下面的示例中,如果我 运行 来自实际列的查询,没问题。我将 first_namelast_name 列连接成 fullname 列别名,然后得到输出。

SELECT first_name ||' '|| last_name AS fullname
FROM actor;

输出:

现在,如果我创建列别名,我会收到错误消息。在此示例中,我将 first_namelast_name 连接成一个 fullname 列别名,然后查询 value1 和 value2.

之间的名称
SELECT first_name ||' '|| last_name AS fullname
FROM actor;
WHERE fullname BETWEEN 'Zero Cage' AND 'Fred Costner';

输出:

提前感谢您抽出宝贵时间提供帮助!

In postgres document:

An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.

根据 SQL 标准,可能不是很直观。这背后的(历史)原因是 SELECT 查询中的事件序列。 WHEREHAVING 在考虑列别名之前解析,而 GROUP BYORDER BY 稍后发生,在应用列别名之后。 另请注意,输入和输出名称之间的冲突在 ORDER BY 和 GROUP BY 中的解决方式不同 - 另一个历史怪事(背后有原因,但仍然可能令人困惑)。

您可以使用以下方式之一:

  1. 使用完整的两列名称
SELECT first_name || ' ' || last_name AS fullname
FROM actor
WHERE first_name || ' ' || last_name BETWEEN :conditio1 AND :conditio2
  1. 使用 CTE
WITH data s (
  SELECT first_name || ' ' || last_name AS fullname
  FROM actor
)
SELECT *
FROM data
WHERE fullname BETWEEN :conditio1 AND :conditio2
  1. 使用子查询
SELECT *
FROM (
  SELECT first_name || ' ' || last_name AS fullname
  FROM actor
) tmp
WHERE tmp.fullname BETWEEN :conditio1 AND :conditio2