MySQL:有没有办法减少这么多视图的创建

时间:2012-06-11 15:12:49

标签: mysql performance oracle query-optimization

我有三张这样的表:

表1结构:
姓名:registered_applicant_details
字段:applicant_id INT PRIMARY_KEY,state_id INT;

表2结构:
名称:oc_shortlisted_candidates
字段:candidate_id; >>>哪个是外键是指registered_applicant_details中的applicant_id

表3结构:
名称:oc_selected_candidates
字段:candidate_id; >>>哪个是外键是指registered_applicant_details中的applicant_id

我想要这样的结果集:state_wise_counts

state_id | shortlisted_count | selected_counts

我获得结果的方法是

第1步:我创建了两个这样的视图

CREATE VIEW  state_wise_shortlisted_count AS 
    (select rad.state_id AS state_id,
             count(0) AS shortlisted 
      from (oc_shortlisted_candidates oec 
             join registered_applicant_details rad) 
      where (oec.candidate_id = rad.applicant_id) 
      group by rad.state_id);

CREATE VIEW state_wise_selected_count AS 
      (select rad.state_id AS state_id,
               count(0) AS selected 
      from (oc_selected_candidates oec 
            join registered_applicant_details rad)
      where (oec.candidate_id = rad.applicant_id) 
      group by rad.state_id);

第2步:现在再次使用state_id

加入这两个视图
SELECT s.state_id, sho.shortlisted, sel.selected
FROM statewise_shortlisted_count sho
JOIN statewise_selected_count sel ON sel.state_id = sho.state_id;

我的方法中的缺点

由于我们有两个外来表,即(shortlisted_candidates& selected_candidates),我创建了两个视图,但是如果我们有10个表的意思,我需要创建10个视图。
所以对于“state_wise计数”,我们需要创建10个视图, 如果存在另外一个属性,即“城市”,则如果我们想再次“city_wise_counts”,我需要再创建10个视图 我认为这不是正确的方法。

请建议我正确的解决方案。
注意:我不想使用子查询,因为这些表有大约10,000个记录和&我需要减少来自应用程序的数据库调用

1 个答案:

答案 0 :(得分:1)

不确定您对子查询的性能意味着什么。对于投影中的每个计数,您当前的代码会从RAD表中读取一次。子查询怎么会更糟?

尝试这样的事情:

select rad.state_id AS state_id
         ,  sum (case when oslc.candidate_id is not null then 1 else 0 end) AS shortlisted
         ,  sum (case when osec.candidate_id is not null then 1 else 0 end) AS selected
from registered_applicant_details rad
     left outer join oc_shortlisted_candidates oslc 
          on (rad.applicant_id = oslc.candidate_id) 
     left outer join oc_selected_candidates osec  
          on (rad.applicant_id = osec.candidate_id) 
group by rad.state_id;

警告:未经测试的代码!