【问题标题】:MySQL : Is there any way to reduce creation of so many viewsMySQL:有什么办法可以减少创建这么多视图
【发布时间】:2012-06-11 15:12:48
【问题描述】:

我有三个这样的表:

表1结构:
姓名:registered_applicant_details
字段:application_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 counts”,我们需要创建 10 个视图, 如果还有一个属性,即“城市”,并且如果我们再次想要“city_wise_counts”,我需要再创建 10 个视图。
我认为这不是正确的方法。

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

【问题讨论】:

    标签: mysql performance oracle query-optimization


    【解决方案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;
    

    警告:未经测试的代码!

    【讨论】:

    • 非常感谢,先生。它绝对有效。查询中的一个小变化:选择 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从registered_applicant_details rad左外连接oc_shortlisted_candidates oslc on (rad.applicant_id = oslc.candidate_id) 左外连接oc_selected_candidates osec on (rad.applicant_id = osec.candidate_id) group by rad.state_id;非常感谢您,先生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多