I have two tables in the database wp_rg_lead_details and wp_service_request. My query is:
$results1=$wpdb->get_results("SELECT * FROM wp_rg_lead_detail WHERE lead_id in ( SELECT entry_id FROM wp_service_request) and form_id =1 AND field_number in (1,39,2)");
When I run this query it is taking too much time causing the page to time out. The inner query is running successfully when executed separately.
There are about 12000 records in both the tables. How should I optimize it so that my page loads faster?
Try to run the inner query seperately and then use its result to fetch data in main query. Try this
$results=$wpdb->get_results("SELECT entry_id FROM wp_service_requests");
$flag = 1;
$str = "(";
foreach ($results as $result) {
if($flag ==1)
{
$str = $str . "'" . $result->entry_id . "'" ;
$flag=2;
}
else
{
$str = $str . ",'" . $result->entry_id . "'" ;
}
}
$str .= ")";
$results1=$wpdb->get_results("SELECT * FROM wp_rg_lead_detail WHERE lead_id in " . $str ." and form_id =1 AND field_number in (1,39,2)");
I recommend if you do not need the full data from the "wp_service_requests" try using filters to minimize the data.