小编Dan*_*pka的帖子

逻辑更改存在与存在限制1

我写了查询

select * from table
where exists (select 1 from table1 where table.column = table1.column)
Run Code Online (Sandbox Code Playgroud)

如果我将其更改为

select * from table
where exists (select 1 from table1 where table.column = table1.column limit 1)
Run Code Online (Sandbox Code Playgroud)

它会改变逻辑吗?

我问是因为计划查询的费用已更改(17000-> 2400)。我使用Postgres 9.4

更新:解释分析两个查询的详细信息

explain (analyze, verbose)
select * from sr_srv_rendered r
where exists (select 1 from sr_res_group rg where rg.id = r.res_group_id and rg.responsible_id = 1)

limit 30

"Limit  (cost=62.06..74.63 rows=30 width=157) (actual time=0.017..0.017 rows=0 loops=1)"
"  Output: r.id, r.bdate, r.comment, r.cost, r.duration, r.edate, r.is_rendered, …
Run Code Online (Sandbox Code Playgroud)

sql postgresql exists limit

4
推荐指数
1
解决办法
1173
查看次数

包含数据修改语句的WITH子句必须处于顶层SQL状态:0A000

我编写了函数,该函数使用WITH构造并将其插入表中,如下所示:

CREATE OR REPLACE FUNCTION test_func()
RETURNS json AS
$BODY$
begin
 return (
   with t as (
     insert into t(id) 
     select 1
     returning *
    )
 select '{"a":"a"}'::json
 );
end;
$BODY$
 LANGUAGE plpgsql VOLATILE;
select test_func()
Run Code Online (Sandbox Code Playgroud)

多数民众赞成返回错误:

ERROR: WITH clause containing a data-modifying statement must be at the top level
SQL-?????????: 0A000
Run Code Online (Sandbox Code Playgroud)

如果执行

   with t as (
     insert into t(id) 
     select 1
     returning *
    )
 select '{"a":"a"}'::json
Run Code Online (Sandbox Code Playgroud)

结果无错误。为什么会发生这种情况以及如何解决呢?

postgresql

3
推荐指数
1
解决办法
735
查看次数

PostgreSQL 如何在递归查询中计算记录数

我想计算节点的所有后代

with recursive t as (
  select a.id, 0 cntr from a 
   where parent_id = 12 union all
  select a.id, cntr + 1 from t 
  join a on a.parent_id = t.id 
   where cntr <= 100
)

select * from t
Run Code Online (Sandbox Code Playgroud)

但这个例子得到了深度计数。我想获得所有后代的不同级别,并限制它。结果是这样的:

12, 0
13, 1
17, 2
...
232, 100
Run Code Online (Sandbox Code Playgroud)

表非常大,选择 * 并计算它 - 不是一个选项 我该怎么做?

postgresql recursion

2
推荐指数
1
解决办法
3099
查看次数

标签 统计

postgresql ×3

exists ×1

limit ×1

recursion ×1

sql ×1