2016-08-24 12 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; 

このクエリは、多くの行を与えるが、c.id=3436のための唯一の1行目:私は別の基準c.id=3436追加するとき

3436 124 'CPU-A' 450 

しかし:

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 

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行を取得

どちらが正しいです!

条件を追加すると、どのように行が増えるのでしょうか?何かが盗まれているように見えます!私はこの問題を引き起こす可能性がどのようなアドバイスをしてください

のPostgreSQL 9.3.3を使用してい

+0

「c.in: 'where c.id = 3436」の推論は、LEFT JOINをプレーン結合に減らします。 – wildplasser

+0

@wildplasserそれは問題ではありません。両方のケースで同じ結果が得られます。 – ban

+1

それは私が言ったことです。 LEFT JOINは、c.idを固定値にする場合は意味がありません。 – wildplasser

答えて

0

これは正しい結果です。理由は、あなたはgroup by a.batchを持っていません。

F.ex.あなたがデータを以下している:12:グループと順序はあなたに1つのユニークなバッチを与えます後

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

はあなたに2ユニークa.batchを与えただろう場所で選択します。

したがって、このクエリを修正するには、選択の最初の変形を条件付きで別のものにラップする必要があります。

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行を生成するので、オタークエリはそれ以上取得できません。 – ban

+0

問題を理解するには、区別のないクエリを実行してください。 –

関連する問題