PostgreSQL如何结合这两个查询?

时间:2019-05-31 15:17:28

标签: sql postgresql

我试图结合这两个查询,但我不知道怎么做

SELECT id FROM comments WHERE thread_id = $1 AND parent_id is NULL

这将返回一个整数。即-5

然后将id结果(5)用于此递归查询

With RECURSIVE recursetree AS
(
 SELECT * FROM comments WHERE comment_id = (use the id 5 here)
 UNION
 SELECT t.*
 From comments t
 JOIN recursetree rt ON rt.comment_id = t.parent_id                         
 )
 SELECT * from recursetree

1 个答案:

答案 0 :(得分:0)

您应该能够将第一个查询放入递归子查询的锚点:

LocalDate date = ...;                                    // get from wherever
date = date.plusMonths(1);                               // go 1 month into the future
int maxDay = date.lengthOfMonth();                       // get max possible day
int randomDayOfMonth = new Random().nextInt(maxDay) + 1; // get random day of month
date = date.withDayOfMonth(randomDayOfMonth);            // set random day of month

还请注意:

  • With RECURSIVE recursetree AS ( SELECT c. FROM comments c WHERE thread_id = $1 UNION ALL SELECT c.* FROM comments c JOIN recursetree rt ON rt.comment_id = c.parent_id ) SELECT * FROM recursetree; UNION ALL更有意义,除非您要承担删除重复项的开销。
  • 表别名UNIONc的含义比任意字母comments更有意义。
  • t建议您使用参数来修饰查询字符串。您应该在查询中使用参数。