Postgresql加入限制

Wei*_* Ma 3 postgresql

我正在创建SQL查询,涉及多个具有1到N关系的表以支持分页.

为了得到前10位父母,我试着去做

SELECT * from parent p
LEFT JOIN child c
ON c.parent_id = p.id
LIMIT 10
Run Code Online (Sandbox Code Playgroud)

如果任何父级有多个子级,则此方法无效

我能做的一个选择是

__CODE__

这非常笨拙.我想做的是

SELECT * from parent LIMIT 10 into temp_p;
SELECT * from temp_p p
LEFT JOIN child c
ON c.parent_id = p.id
Run Code Online (Sandbox Code Playgroud)

但当然语法错了.我想知道Postgresql是否有某种方式来支持我想做的事情.

jme*_*sky 8

使用公用表表达式:

WITH ten_parents AS (
  SELECT * from parent LIMIT 10)
SELECT *
  FROM ten_parents p
    LEFT JOIN child c
      ON c.parent_id = p.id
Run Code Online (Sandbox Code Playgroud)

  • 你不需要CTE,一个简单的派生表(`select*from(select*from parent limit 10)p ...`)也可以.并不是说CTE当然是错的. (2认同)