我有三个这样的表:
表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/