user1449197
user1449197

Reputation: 53

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

I have three tables like this:

Table 1 structure:
Name: registered_applicant_details
Fields: applicant_id INT PRIMARY_KEY, state_id INT;

Table 2 structure:
Name: oc_shortlisted_candidates
Fields: candidate_id; >>> Which is a foreign Key refers to applicant_id in registered_applicant_details

Table 3 structure:
Name: oc_selected_candidates
Fields: candidate_id; >>> Which is a foreign Key refers to applicant_id in registered_applicant_details

I want result set like this : state_wise_counts

state_id | shortlisted_count | selected_counts

My approach to get the result is

Step 1: I have created two views like this

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);

Step 2: Now again joined those two views with 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;

Drawbacks in my approach

As we have two foreign tables i.e. (shortlisted_candidates & selected_candidates) I am creating two view, but if we have like that some 10 tables means, I need to create 10 views.
So for “state_wise counts” we need to create 10 views, If one more attribute i.e. "city" is present & if we want “city_wise_counts” again I need to create 10 more views.
I think this is not the right way.

Please suggest me with right solution.
Note: I don't want to use sub-queries, because those tables have some 10,000 record & I need to reduce the number of db calls from application

Upvotes: 1

Views: 81

Answers (1)

APC
APC

Reputation: 146249

Not sure what you mean about the performance of sub-queries. Your current code reads from the RAD table once for every count in your projection. How can sub-queries be any worse?

Try something like this:

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;

Caveat: untested code!

Upvotes: 1

Related Questions