-1

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

  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
4

1 回答 1

2

使用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连接条件,因为横向连接引用了上一个表。

于 2020-08-11T04:49:02.203 回答