PostgreSQL 如何使用 with as

Posted

技术标签:

【中文标题】PostgreSQL 如何使用 with as【英文标题】:PostgreSQL how to use with as 【发布时间】:2020-12-09 05:09:56 【问题描述】:

有人知道为什么这不起作用吗?我得到:错误:“most_recent”或附近的语法错误

with most_recent as (SELECT MAX(public."Master_playlist".updated_at)
FROM public."Master_playlist")
SELECT * from public."Playlist"
JOIN public."Master_playlist_playlist" on public."Playlist".id = public."Master_playlist_playlist".playlist_id
JOIN public."Master_playlist" on public."Master_playlist_playlist".master_playlist_id = public."Master_playlist".id
WHERE public."Master_playlist".updated_at = most_recent;

应该从 Master_playlist 获取最新日期,然后使用它来选择 Master_playlist 以加入内部查询

谢谢!嗯

【问题讨论】:

【参考方案1】:

with 子句创建一个派生表,您需要从中选择,使用 join 或子查询。您还需要为该列设置别名,以便以后可以引用它,如下所示:

with most_recent as (
    SELECT MAX(updated_at) max_updated_at
    FROM public."Master_playlist"
)
SELECT * 
from public."Playlist"
JOIN public."Master_playlist_playlist" 
    on public."Playlist".id = public."Master_playlist_playlist".playlist_id
JOIN public."Master_playlist" 
    on public."Master_playlist_playlist".master_playlist_id = public."Master_playlist".id
WHERE public."Master_playlist".updated_at = (SELECT max_updated_at FROM most_recent)

但是在这里,使用行限制查询似乎更简单:

select ...
from (
    select *
    from public."Master_playlist"
    order by updated_at desc
    limit 1
) mp
inner join public."Master_playlist_playlist" mpp
    on mpp.master_playlist_id = mp.id
inner join public."Playlist" p
    on p.id = mpp.playlist_id

【讨论】:

以上是关于PostgreSQL 如何使用 with as的主要内容,如果未能解决你的问题,请参考以下文章

mybatis+postgresql WITH RECURSIVE cte as

sql里面 with...as 是啥意思啊?如何使用

with as 如何工作

使用“with open() as file”方法,如何多次写入? [复制]

`with canvas:` (Python `with something() as x:`) 如何在 Kivy 中隐式工作?

在 PostgreSQL 中为临时变量分配特定的数据类型