如何在内部查询列中使用外部查询列

时间:2018-08-14 08:50:35

标签: sql postgresql

我正在尝试在下面运行PostgreSQL查询

SELECT *
FROM user_follow uf
       INNER JOIN (SELECT uplr.post, COUNT(*)
                   FROM user_post_like_relation uplr
                   WHERE uplr.category = 'like' AND uf.recently_viewed < uplr.created_at . //CANNOT reference uf
                     AND clicked = true
                   GROUP BY uplr.post) uplr
    ON uplr.post = uf.post
INNER JOIN post p ON uf.post = p.id

不幸的是,我无法在INNER JOIN查询中引用uf,但我必须加入并在JOIN查询中引用last_viewed列,这一点很重要。有办法克服吗?

2 个答案:

答案 0 :(得分:0)

如果要引用以前的INNER JOIN LATERAL列表条目中的列,则必须使用FROM

可从PostgreSQL 9.3开始使用。

答案 1 :(得分:0)

我认为在您的情况下,只需JOIN到表中并GROUP个结果即可执行COUNT

SELECT uf.post, p.id, count(*)
FROM user_follow uf
JOIN post p ON uf.post = p.id
JOIN user_post_like_relation uplr ON uplr.post = uf.post
WHERE uplr.category = 'like'
  AND clicked = 'true'
  AND uf.recently_viewed < uplr.created_at
GROUP BY uf.post, p.id

SELECTGROUP BY列以获取所需的列。