sql - 选择所有使用别名的地方

标签 sql postgresql

我创建了一个这样的表:

CREATE TABLE test (
  id INT,
  name VARCHAR(255),
  birthdate DATE
);

INSERT INTO test (id, name, birthdate) VALUES (1, 'jhon', '1975-12-12');
INSERT INTO test (id, name, birthdate) VALUES (2, 'doe', '1994-12-12');

并尝试这样查询:

select * 
from (
    select extract(year from age(birthdate)) as age from test
) d
where d.age >= 24

它在大多数情况下都有效。我想要的是能够在 age 别名上使用 WHERE 进行查询。问题是我需要在另一个查询中“封装” 它,因为我已经在论坛中读到我不能在别名中使用 WHERE 除非像这样使用。

问题:它只返回 age,即使添加 select * 它也不返回其他字段,我做错了什么?

如果您想观看现场直播:https://www.db-fiddle.com/f/qA8znjMzm4NR9wdCo5pssX/0

最佳答案

it's returning only the age, even adding select * it's not returning the other fields

然后,子查询中的 SELECT * 也是:

select * 
from (
    select t.*, extract(year from age(birthdate)) as age from test t
) d
where d.age >= 24

或者只是删除子查询并重复表达式:

select t.*, extract(year from age(birthdate)) as age
from test t
where extract(year from age(birthdate)) >= 24

关于sql - 选择所有使用别名的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58053408/

相关文章:

Mysql - 聚合函数非常慢

sql - 如何使用 "time"字段在 postgresql 中按小时分组?

postgresql - JDL如何使用类抽象?

sql - Athena 嵌套结构查询 - 如何在 SQL 中查询 Value_counts

php - 为什么PHP在mysql表数据库中插入变量名

MYSQL 内部连接与计数子查询

mysql - 按 HH :MM in a MySQL query 分组

sql - PostgreSQL 中的时间窗口

SQL - 优化批量插入和大型连接的性能?

PostgreSQL:pg_dump:[archiver (db)] 连接到数据库 "dbase"失败:致命:用户 "postgres"的对等身份验证失败