【问题标题】:PostgreSQL Lateral join when right table row doesn't exist右表行不存在时的PostgreSQL横向连接
【发布时间】:2020-11-30 17:35:06
【问题描述】:

当我的数据库中有一个没有帖子的类别时,结果选择返回没有空类别的行。如何接收一个空类别的表格。

  SELECT
    c.id as category_id,
    pp.id as post_id
  FROM categories c,
  LATERAL
  (SELECT
    id
  FROM posts
  WHERE c.id = posts.category_id
   ORDER BY views DESC
   LIMIT 2) pp
  ORDER BY c.category ASC, pp.id ASC

当前查询结果:

category_id | post_id
----------------------
1           | 1
1           | 2
3           | 3
3           | 4

我需要:

category_id | post_id
----------------------
1           | 1
1           | 2
2           |
3           | 3
3           | 4

【问题讨论】:

    标签: sql postgresql join postgresql-9.6 lateral-join


    【解决方案1】:

    使用left join:

    SELECT
        c.id as category_id,
        pp.id as post_id
    FROM categories c
    LEFT JOIN LATERAL
    (SELECT
        id
    FROM posts
    WHERE c.id = posts.category_id
        ORDER BY views DESC
        LIMIT 2) pp ON TRUE
    ORDER BY c.category ASC, pp.id ASC
    

    请注意,我使用on true 作为连接条件,因为横向连接引用了上一个表。

    【讨论】:

    • 谢谢!在您写作时,我找到了一个有效的LEFT JOIN,但我错过了on true。非常感谢您的通知!
    • @UliankaShu 没问题,考虑投票并接受答案
    猜你喜欢
    • 1970-01-01
    • 2020-08-09
    • 2020-08-25
    • 2021-02-21
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2016-06-21
    相关资源
    最近更新 更多