Postgresql查询为更广泛的搜索提供更少的结果

Postgresql查询为更广泛的搜索提供更少的结果,sql,postgresql,Sql,Postgresql,我面临着一个非常棘手的问题 我的查询非常复杂,所以我将使用一个更简单的版本 select distinct on (a.batch) c.id,a.partid,b.partname,c.stock_stock, from components a join parts b using(partid) left join (select * from componentsreport($1)) c using (partid) JOIN start_work d on d.batchid=a.

我面临着一个非常棘手的问题

我的查询非常复杂,所以我将使用一个更简单的版本

select distinct on (a.batch) c.id,a.partid,b.partname,c.stock_stock,
from components a 
join parts b using(partid)
left join (select * from componentsreport($1)) c using (partid)
JOIN start_work d on d.batchid=a.batchid
where  b.issub
group by c.id,a.partid,b.partname,c.stock
order by a.batch;
此查询提供了许多行,但对于c.id=3436,只提供了一行:

但是,当我添加另一个标准c.id=3436时:

我得到6行:

3436 124  'CPU-A' 450
3436 125  'CPU-A' 130
3436 125  'CPU-A' 660
3436 126  'CPU-A' 0
3436 127  'CPU-A' 40
3436 128  'CPU-A' 40
这是正确的

我不明白当我添加更多的条件时,如何得到更多的行?好像有什么东西被窃听了

我正在使用PostgreSQL 9.3.3


请告知可能导致此问题的原因。

这是正确的结果。原因是,您没有按批分组,只有distinct

F.ex。您有以下数据:

c.id = 3436, a.batch = 1
c.id = 3436, a.batch = 2
c.id = 3437, a.batch = 1
c.id = 3437, a.batch = 2
选择distinct after group,订单将为您提供1个唯一批次=1

选择将为您提供2个唯一a批次的位置:1、2

所以,要修复此查询,需要将select的第一个变量包装为另一个带有条件的变量

select * 
from (
   select distinct on (a.batch) c.id,a.partid,b.partname,c.stock_stock,
   from components a 
      join parts b using(partid)
      left join (
         select * 
         from componentsreport($1)
      ) c using (partid)
      JOIN start_work d on d.batchid=a.batchid
   where  b.issub
   group by c.id,a.partid,b.partname,c.stock
   order by a.batch
) tmp 
where tmp.id = 3436

关于c。in:其中c.id=3436将把左连接减少为普通连接。@wildplasser这没关系。在这两种情况下,内部联接给出相同的结果。这就是我所说的。如果将c.id强制为固定值,则左连接没有意义。不相关,但是:左连接选择*来自组件报告$1 c可以简化为左连接组件报告$1 cI我不确定我是否了解需要执行的操作。这并不能解决问题。内部查询仍然会生成1行,因此otter查询不会得到更多的u。要理解问题,请尝试在不使用distinct的情况下执行查询。此外,您是否可以准备一些沙盒或架构数据,以便我们也可以检查它。
c.id = 3436, a.batch = 1
c.id = 3436, a.batch = 2
c.id = 3437, a.batch = 1
c.id = 3437, a.batch = 2
select * 
from (
   select distinct on (a.batch) c.id,a.partid,b.partname,c.stock_stock,
   from components a 
      join parts b using(partid)
      left join (
         select * 
         from componentsreport($1)
      ) c using (partid)
      JOIN start_work d on d.batchid=a.batchid
   where  b.issub
   group by c.id,a.partid,b.partname,c.stock
   order by a.batch
) tmp 
where tmp.id = 3436