我知道,这个查询(不正确,只是一个例子)可以用其他方式编写。但是,我有兴趣在存在这种关系时使用 WITH
m.user_id = u.id
。是否可以? https://www.postgresql.org/docs/current/queries-with.html - 看起来 WITH 只用于准备好的数据,而不是动态的。
with last_message as (
select m.message
from messages m
where m.user_id = u.id
order by m.id desc
limit 1
)
select u.*, last_message
from users u
where last_message = 'some_message';
附言不明白,为什么 Postgres 限制我们子查询有变量(作为将要执行的语句),所以我们可以很容易地在 select 和 where 子句中使用这个变量。 目前,我必须从 select 子句中复制子查询并在 where 子句中使用它(