2016-07-14 8 views
0

Ich habe einige „kompliziert“ Abfrage konfrontiert, wie:Auswahlabfrage und gleiche Abfrage mit mit Ergebnissen

with q1 as (
select w.entity_id, p.actionable_group, p.error_type 
from issue_analysis p 
join log l on p.id = l.issue_analysis_id 
join website w on l.website_id = w.id 
where l.date >= '2016-06-01' 
group by 1, 2, 3 
), 
q2 as (
select w.entity_id, p.actionable_group, p.error_type 
from issue_analysis p 
join log l on p.id = l.issue_analysis_id 
join website w on l.website_id = w.id 
where l.date >= '2016-06-01' 
group by 1, 2, 3 
having count(1) = 1 
) 

und versuchte zu

SELECT q1.entity_id, count(q1.entity_id), count(q2.entity_id) 
from q1, q2 
group by 1 
order by 1 

aber Ergebnis bietet für mich eine „falsche“ Daten, weil es nicht wirklich beide zählt ...

Könnten Sie bitte die "sauberere" Möglichkeit beschreiben, ein solches Problem ohne viele verschachtelte Abfragen zu lösen?

wenn es hilfreich sein kann - q2 ist ähnlich wie q1 aber mit having count(1) = 1 am Ende.

P.S. Dokumentation Verbindung wird in Ordnung sein, ist die Antwort einfach.

+0

Vermutlich brauchen Sie einen Beitritt. Einfache Regel: * Immer * explizite 'JOIN'-Syntax verwenden. * Niemals * Kommas in der FROM-Klausel verwenden. –

+0

Ich habe versucht, q1 links Join q2 auf q1.entity_id = q2.entity_id zu verwenden, aber es schlägt auch fehl. –

Antwort

0

Sie erhalten ohne Zweifel ein kartesisches Produkt und dies wirkt sich auf die Aggregation aus. Stattdessen aggregieren vor macht die Joins:

select q1.entity_id, q1_cnt, q2_cnt 
from (select q1.entity_id, count(*) as q1_cnt 
     from q1 
     group by q1.entity_id 
    ) q1 join 
    (select q2.entity_id, count(*) as q2_cnt 
     from q2 
     group by q2.entity_id 
    ) q2 
    on q1.entity_id = q2.entity_id; 
+0

Danke, @Gordon –

Verwandte Themen