2016-07-14 110 views
0

我已经遇到了一些“复杂”的查询,如:选择查询和相同的查询具有结果

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 
) 

并试图

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

但结果提供给我一个“错误”的数据,因为它不是真的包含两个计数...

请问您能描述一下最“清洁”的方式来解决这个问题,而没有大量的嵌套查询吗?

如果它可能会有所帮助 - q2是类似于q1但末尾having count(1) = 1

P.S. 文档链接会很好,答案很简单。

+0

大概你需要一个连接。简单的规则:*总是*使用明确的'JOIN'语法。 *从不*在'FROM'子句中使用逗号。 –

+0

我试过在q1.entity_id = q2.entity_id上使用q1 left join q2,但它也失败了。 –

回答

0

毫无疑问,您得到一个笛卡尔积,这会影响聚合。相反,聚合之前做连接:

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

谢谢@戈登 –