2016-08-24 58 views
-1

我正面臨一個非常奇怪的問題,其中查詢。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.batchid 
where b.issub 
group by c.id,a.partid,b.partname,c.stock 
order by a.batch; 

這個查詢提供了許多行,但只有1 c.id=3436行:

3436 124 'CPU-A' 450 

然而,當我添加另一個標準c.id=3436

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 c.id=3436 and b.issub 
group by c.id,a.partid,b.partname,c.stock 
order by a.batch; 

我得到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

請指教一下可能會導致此問題。

+0

對'c.'的推論:'其中c.id = 3436'將減少你的左連接到一個普通連接。 – wildplasser

+0

@wildplasser沒關係。內連接在兩種情況下都會產生相同的結果 – ban

+1

這就是我所說的。如果您將c.id強制爲固定值,則「左連接」無效。 – wildplasser

回答

0

這是正確的結果。原因是,你沒有group by a.batch,只有不同。

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 

選擇組後,不同的秩序會送給你1個唯一的批次= 1

選擇與在會送給你2獨特a.batch:12

因此,要解決此查詢,您需要將第一個選擇變體包裝到另一個具有條件的變體中。

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 
+0

我不知道我明白我需要做什麼。 – ban

+0

這並不能解決問題。內部查詢仍然產生1行,所以otter查詢不會獲得更多。 – ban

+0

要理解問題,請嘗試執行無區別的查詢。 –