MySQL : Is there any way to reduce creation of so many views

标签 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 步:我创建了两个这样的 View

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 加入这两个 View

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)我正在创建两个 View ,但是如果我们有 10 个表意味着,我需要创建 10 个 View 。
因此,对于“state_wise counts”,我们需要创建 10 个 View , 如果存在另一个属性,即“city”,并且如果我们再次需要“city_wise_counts”,我需要再创建 10 个 View 。
我认为这不是正确的方法。

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

最佳答案

不确定您所说的子查询性能是什么意思。您当前的代码会针对投影中的每个计数从 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;

警告:未经测试的代码!

关于MySQL : Is there any way to reduce creation of so many views,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10982870/

相关文章:

php - 使用工厂类查询数据库如何提高效率

IronPython 中质量评估表达式的性能

javascript - 优化设置多个内联 css 样式的性能

algorithm - F# FSharpMap 与字典性能

docker中的Oracle xe 11g,在ubuntu上重新启动docker后创建的用户丢失

sql - Oracle SQL : Get the previous values

c# - 如何保存每周、每两周和每月的订单

mysql - sql连接具有相同外键的2个表

java - servlet 到 mysql jdbc 连接类未找到异常

Oracle AWR - 高 SQL 解析调用但 0 次执行