Improving the Performance of this Stored Procedure in MySQL - mysql
I am attempting to optimize this Stored Procedure. Currently, this iteration when done from the very top of the chain, can take about 2.4-2.7 seconds. I would love to get this down to below 1 second if possible.
I have done research on what I can do to optimize this and most of MySQL's own tips do not work. You cannot LOCK tables or use the LOAD DATA statements inside Stored Procedures. When running tests, it appears that the INSERT INTO SELECT statements are taking the most time inside this query.
When I ran one CALL, I got 2.6 seconds with around 13 INSERT INTO statements firing off. At least 3 took 0.43-0.45 seconds to complete. All other statements took very little time to complete.
Here is my current settings inside my 'my.cnf' file:
default-storage-engine = MyISAM
key_buffer_size = 256M
innodb_buffer_pool_size = 3G
innodb_buffer_pool_load_at_startup = ON
innodb_sort_buffer_size = 16M
innodb_flush_method = O_DIRECT
read_buffer_size = 4M
thread_stack = 256K
bulk_insert_buffer_size = 64MB
Here is my Stored Procedure:
BEGIN
DECLARE lastLayer INT;
DECLARE lastInsertCount INT;
DECLARE tempTableRowCount INT;
DROP TABLE IF EXISTS `temp`;
DROP TABLE IF EXISTS `pendingBusiness`;
CREATE TABLE `temp`
(
`layer` INT(5),
`title_c` VARCHAR(255),
`name` VARCHAR(255),
`rep_first_name` VARCHAR(255),
`rep_last_name` VARCHAR(255),
`id_c` CHAR(36),
`contact_status_reps_c` VARCHAR(255),
`phone_mobile` VARCHAR(255),
`contract_type_c` VARCHAR(255),
`email_address` VARCHAR(255)
);
CREATE TABLE `pendingBusiness`
(
`layer` INT(5),
`title_c` VARCHAR(255),
`name` VARCHAR(255),
`rep_first_name` VARCHAR(255),
`rep_last_name` VARCHAR(255),
`id_c` CHAR(36),
`contact_status_reps_c` VARCHAR(255),
`investor_first_name` VARCHAR(255),
`investor_last_name` VARCHAR(255),
`product_detail` VARCHAR(255),
`paperwork_status_c` VARCHAR(255),
`next_step` VARCHAR(255),
`outstanding_requirements_c` VARCHAR(255),
`funding_status_c` VARCHAR(255),
`funding_next_step_c` VARCHAR(255),
`fulfillment_status_c` VARCHAR(255),
`fulfillment_next_step_c` VARCHAR(255),
`amount` VARCHAR(255),
`stage` VARCHAR(255),
`date_entered` DATETIME,
`case_manager` VARCHAR(255),
`lost_sale_date_c` DATETIME,
`compensation_run_c` DATETIME,
`product_id` CHAR(36),
`rep_state` VARCHAR(255),
`investor_state` VARCHAR(255)
);
INSERT INTO `temp`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `phone_mobile`,`contract_type_c`,`email_address`)
SELECT 0,
wn_writing_number_cstm.title_c,
wn_writing_number.`name`,
preps_contracted_reps.first_name,
preps_contracted_reps.last_name,
wn_writing_number_cstm.id_c,
preps_contracted_reps_cstm.contact_status_reps_c,
preps_contracted_reps.phone_mobile,
preps_contracted_reps_cstm.contract_type_c,
email_addresses.email_address
FROM wn_writing_number LEFT OUTER JOIN wn_writing_number_cac_customize_agent_comp_1_c ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing946b_number_ida = wn_writing_number.id
LEFT OUTER JOIN cac_customize_agent_comp ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing3148nt_comp_idb = cac_customize_agent_comp.id
LEFT OUTER JOIN cac_customize_agent_comp_cstm ON cac_customize_agent_comp.id = cac_customize_agent_comp_cstm.id_c
LEFT OUTER JOIN aos_products_cac_customize_agent_comp_1_c ON cac_customize_agent_comp_cstm.id_c = aos_products_cac_customize_agent_comp_1_c.aos_produca2b8nt_comp_idb
LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
LEFT OUTER JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = preps_contracted_reps_cstm.id_c
LEFT OUTER JOIN email_addresses ON email_addr_bean_rel.email_address_id = email_addresses.id
LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
WHERE wn_writing_number_cstm.wn_writing_number_id_c = passId AND wn_writing_number.deleted = '0' AND preps_contracted_reps.deleted = '0' AND wn_writing_number.deleted = '0' AND email_addr_bean_rel.deleted = '0'
GROUP BY wn_writing_number.`name`;
INSERT INTO `pendingBusiness`(`title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`)
SELECT
wn_writing_number_cstm.title_c,
wn_writing_number.`name`,
preps_contracted_reps.first_name,
preps_contracted_reps.last_name,
wn_writing_number_cstm.id_c,
preps_contracted_reps_cstm.contact_status_reps_c,
contacts.first_name,
contacts.last_name,
aos_products.`name`,
opportunities_cstm.paperwork_status_c,
opportunities.next_step,
opportunities_cstm.outstanding_requirements_c,
opportunities_cstm.funding_status_c,
opportunities_cstm.funding_next_step_c,
opportunities_cstm.fulfillment_status_c,
opportunities_cstm.fulfillment_next_step_c,
opportunities.amount,
opportunities_cstm.stage_c,
opportunities.date_entered,
CONCAT(users.first_name, " ", users.last_name) AS case_manager,
opportunities_cstm.lost_sale_date_c,
opportunities_cstm.compensation_run_c,
aos_products.id,
preps_contracted_reps.primary_address_state,
opportunities_cstm.state_of_residence_c
FROM wn_writing_number
LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
LEFT OUTER JOIN opportunities_cstm ON opportunities_cstm.wn_writing_number_id_c = wn_writing_number.id
LEFT OUTER JOIN contacts ON opportunities_cstm.contact_id_c = contacts.id
LEFT OUTER JOIN opportunities ON opportunities_cstm.id_c = opportunities.id
LEFT OUTER JOIN aos_products ON opportunities_cstm.aos_products_id_c = aos_products.id
LEFT OUTER JOIN users ON opportunities_cstm.user_id_c = users.id
WHERE wn_writing_number.id = passId AND opportunities.deleted = '0' AND opportunities.date_entered >= DATE_SUB(NOW(),INTERVAL 1.5 YEAR)
GROUP BY opportunities_cstm.id_c;
SET lastLayer := 0;
SET lastInsertCount := 1;
LayerLoop: WHILE lastInsertCount > 0 DO
INSERT INTO `temp`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `phone_mobile`,`contract_type_c`,`email_address`)
SELECT lastLayer + 1,
wn_writing_number_cstm.title_c,
wn_writing_number.`name`,
preps_contracted_reps.first_name,
preps_contracted_reps.last_name,
wn_writing_number_cstm.id_c,
preps_contracted_reps_cstm.contact_status_reps_c,
preps_contracted_reps.phone_mobile,
preps_contracted_reps_cstm.contract_type_c,
email_addresses.email_address
FROM wn_writing_number LEFT OUTER JOIN wn_writing_number_cac_customize_agent_comp_1_c ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing946b_number_ida = wn_writing_number.id
LEFT OUTER JOIN cac_customize_agent_comp ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing3148nt_comp_idb = cac_customize_agent_comp.id
LEFT OUTER JOIN cac_customize_agent_comp_cstm ON cac_customize_agent_comp.id = cac_customize_agent_comp_cstm.id_c
LEFT OUTER JOIN aos_products_cac_customize_agent_comp_1_c ON cac_customize_agent_comp_cstm.id_c = aos_products_cac_customize_agent_comp_1_c.aos_produca2b8nt_comp_idb
LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
LEFT OUTER JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = preps_contracted_reps_cstm.id_c
LEFT OUTER JOIN email_addresses ON email_addr_bean_rel.email_address_id = email_addresses.id
LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
WHERE wn_writing_number_cstm.wn_writing_number_id_c IN (SELECT id_c FROM `temp` WHERE layer = lastLayer) AND wn_writing_number.deleted = '0' AND preps_contracted_reps.deleted = '0' AND wn_writing_number.deleted = '0' AND email_addr_bean_rel.deleted = '0'
GROUP BY wn_writing_number.`name`;
SET lastInsertCount := ROW_COUNT();
INSERT INTO `pendingBusiness`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`)
SELECT lastLayer + 1,
wn_writing_number_cstm.title_c,
wn_writing_number.`name`,
preps_contracted_reps.first_name,
preps_contracted_reps.last_name,
wn_writing_number_cstm.id_c,
preps_contracted_reps_cstm.contact_status_reps_c,
contacts.first_name,
contacts.last_name,
aos_products.`name`,
opportunities_cstm.paperwork_status_c,
opportunities.next_step,
opportunities_cstm.outstanding_requirements_c,
opportunities_cstm.funding_status_c,
opportunities_cstm.funding_next_step_c,
opportunities_cstm.fulfillment_status_c,
opportunities_cstm.fulfillment_next_step_c,
opportunities.amount,
opportunities_cstm.stage_c,
opportunities.date_entered,
CONCAT(users.first_name, " ", users.last_name) AS case_manager,
opportunities_cstm.lost_sale_date_c,
opportunities_cstm.compensation_run_c,
aos_products.id,
preps_contracted_reps.primary_address_state,
opportunities_cstm.state_of_residence_c
FROM wn_writing_number
LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
LEFT OUTER JOIN opportunities_cstm ON opportunities_cstm.wn_writing_number_id_c = wn_writing_number.id
LEFT OUTER JOIN contacts ON opportunities_cstm.contact_id_c = contacts.id
LEFT OUTER JOIN opportunities ON opportunities_cstm.id_c = opportunities.id
LEFT OUTER JOIN aos_products ON opportunities_cstm.aos_products_id_c = aos_products.id
LEFT OUTER JOIN users ON opportunities_cstm.user_id_c = users.id
WHERE opportunities.deleted = '0' AND wn_writing_number_cstm.wn_writing_number_id_c IN (SELECT id_c FROM `temp` WHERE layer = lastLayer) AND opportunities.date_entered >= DATE_SUB(NOW(),INTERVAL 1.5 YEAR)
GROUP BY opportunities_cstm.id_c;
SET lastLayer := lastLayer + 1;
END WHILE LayerLoop;
SELECT `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`
FROM `pendingBusiness`
ORDER BY rep_first_name ASC;
DROP TABLE IF EXISTS `pendingBusiness`;
END
FWIW, your query is functionally identical to the following. However, the following has the advantage of being easier to read. That said, your GROUP BY clause will return (potentially) indeterminate results for all but name.
SELECT 0
, k.title_c
, a.name
, g.first_name
, g.last_name
, k.id_c
, h.contact_status_reps_c
, g.phone_mobile
, h.contract_type_c
, j.email_address
FROM wn_writing_number a
JOIN wn_writing_number_cac_customize_agent_comp_1_c b
ON b.wn_writing946b_number_ida = a.id
JOIN cac_customize_agent_comp c
ON c.id = b.wn_writing3148nt_comp_idb
LEFT
JOIN cac_customize_agent_comp_cstm d
ON d.id_c = c.id
LEFT
JOIN aos_products_cac_customize_agent_comp_1_c e
ON e.aos_produca2b8nt_comp_idb = d.id_c
LEFT
JOIN preps_contracted_reps_wn_writing_number_1_c f
ON f.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = a.id
JOIN preps_contracted_reps g
ON g.id = f.preps_cont9effed_reps_ida
LEFT
JOIN preps_contracted_reps_cstm h
ON h.id_c = g.id
JOIN email_addr_bean_rel i
ON i.bean_id = h.id_c
LEFT
JOIN email_addresses j
ON j.id = i.email_address_id
JOIN wn_writing_number_cstm k
ON k.id_c = a.id
WHERE k.wn_writing_number_id_c = passId
AND a.deleted = 0
AND g.deleted = 0
AND i.deleted = 0
GROUP
BY a.name;
Related
How can I speed up this query with mysqli?
I have this query and it take 117 seconds to get 100000 rows can me get all this rows on 5 seconds or 10 seconds? SELECT `nas`.`nasname`, `nas`.`api_username`, `nas`.`api_password`, `nas`.`api_port`, `nas`.`secret`, `nas`.`up_by`, COALESCE(`nas`.`api_is_enabled`,'0') as `api_is_en`, `radacct`.`nasipaddress`, `radcheck`.`address_list_name`, `radcheck`.`address_val`, `radacct`.`framedipaddress`, `radacct`.`callingstationid`, `radacct`.`radacctid` as `id_session`, `radacct`.`framedprotocol`, `radacct`.`username`, `radacct`.`last_speed` , `radacct`.`acctsessionid` as `acctsessionid`, `radip`.`value` as `ip_address`, `radmac`.`value` as `mac_address`, `radcount`.`value` as `simul_sess`, COUNT(`radacct`.`radacctid`) as count_login , COALESCE(`card_users`.`id`,0) as `id_card`, COALESCE(`card_users`.`download_qouta`,`userinfo`.`in_down`) *1024*1024 as `down_qouta`, COALESCE(`card_users`.`upload_qouta`,`userinfo`.`in_up`) *1024*1024 as `up_qouta`, COALESCE(`card_users`.`all_quota`,`userinfo`.`av_qouta`) *1024*1024 as `av_qouta`, `card_users`.`date_end_card` as `date_end_card`, `card_users`.`val_date` as `val_date`, `card_users`.`per_second` as `per_second`, `card_users`.`at_the_first_login` as `at_the_first_login`, `card_users`.`exp_first_login` as `exp_first_login`, `card_users`.`val_time_exp` as `val_time_exp`, `card_users`.`time_cards_exp` as `time_cards_exp`, `card_users`.`exp_quota` as `exp_quota`, `card_users`.`exp_date` as `exp_date`, `userinfo`.`updatedate` as `updatedate`, `userinfo`.`divi_down_speed_slm` as `divi_down_speed_slm`, `userinfo`.`divi_up_speed_slm` as `divi_up_speed_slm`, `userinfo`.`arr_days` as `u_arr_days`, `userinfo`.`value_choice` as `u_value_choice`, `userinfo`.`last_end_day` as `last_end_day`, `userinfo`.`macs` as `macs`, `p`.`profile_name` as `profile_name`, `p`.`daily_down_qouta`*1024*1024 as `down_daily_qouta`, `p`.`daily_up_qouta`*1024*1024 as `up_daily_qouta`, `p`.`daily_profile_qouta`*1024*1024 as `daily_profile_qouta`, `p`.`online_time` as `online_time`, `p`.`hours_min` as `hours_min`, `p`.`daily_online_time` as `daily_online_time`, `p`.`daily_hours_min` as `daily_hours_min`, `p`.`bandwidth_time` as `bandwidth_time`, `p`.`daily_expire_service` as `daily_expire_service`, `p`.`qouta_expire_service` as `qouta_expire_service`, `p`.`profile_expire_service` as `profile_expire_service`, `p`.`sp_up` as `sp_up`, `p`.`sp_down` as `sp_down`, `p`.`ch_day_end` as `ch_day_end`, `p`.`set_day_end` as `set_day_end`, `p`.`percent` as `percent`, `p`.`arr_days` as `p_arr_days`, `p`.`value_choice` as `p_value_choice`, `r1`.`value` as `value_exp`, `p1`.`bandwidth_time` as `band_exp`, `p1`.`percent` as `percent_exp`, `r2`.`value` as `val_address_exp_list`, `r3`.`value` as `value_exp_daily`, `p3`.`bandwidth_time` as `band_daily_exp`, `p3`.`percent` as `percent_daily_exp`, `r4`.`value` as `val_address_exp_daily_list`, `r5`.`value` as `value_exp_serv`, `p3`.`bandwidth_time` as `band_serv_exp`, `p3`.`percent` as `percent_serv_exp`, `r6`.`value` as `val_address_exp_serv_list`, `r7`.`value` as `value_now`, `r8`.`value` as `val_address_list`, COALESCE(ROUND(time_to_sec(`userinfo`.`online_time`)),0) as `t_online_time` , COALESCE(ROUND(time_to_sec(`userinfo`.`daily_online_time`)),0) as `d_online_time`, UNIX_TIMESTAMP(STR_TO_DATE(`radexp`.`value`, '%d %b %Y %H:%i')) as `exp_user`, `radacct`.`callingstationid` as `callingstationid`, UNIX_TIMESTAMP(STR_TO_DATE(`radacct`.`acctstarttime`, '%Y-%m-%d %H:%i:%s')) as `session_st_date` FROM `radacct` INNER JOIN `radcheck` ON `radacct`.`username` = `radcheck`.`username` AND `radcheck`.`attribute` = 'Cleartext-Password' INNER JOIN `radusergroup` `r9` ON `r9`.`username` = `radcheck`.`username` LEFT JOIN `userinfo` ON `userinfo`.`username` = `r9`.`username` LEFT JOIN ( SELECT SUM(`radacct`.`acctinputoctets`) as `up_today` , SUM(`radacct`.`acctoutputoctets`) as `down_today` , SUM(`radacct`.`acctsessiontime`) as `daily_time` , `radacct`.`username` FROM `radacct` WHERE DATE_FORMAT(STR_TO_DATE(`acctstarttime`,'%Y-%m-%d %H:%i:%s'),'%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d') GROUP BY `username` ) as `rad2` ON `rad2`.`username` = `r9`.`username` INNER JOIN `nas` ON `nas`.`nasname`=`radacct`.`nasipaddress` LEFT JOIN `profiles` `p` ON `p`.`profile_name` = `r9`.`groupname` LEFT JOIN `profiles` `p1` ON `p1`.`id` = `p`.`qouta_expire_service` LEFT JOIN `profiles` `p2` ON `p2`.`id` = `p`.`daily_expire_service` LEFT JOIN `profiles` `p3` ON `p3`.`id` = `p`.`profile_expire_service` LEFT JOIN `radgroupreply` `r1` ON `r1`.`groupname` = `p1`.`profile_name` AND `r1`.`attribute` = 'Mikrotik-Rate-Limit' LEFT JOIN `radgroupreply` `r2` ON `r2`.`groupname` = `p1`.`profile_name` AND `r2`.`attribute` = 'Mikrotik-Address-List' LEFT JOIN `radgroupreply` `r3` ON `r3`.`groupname` = `p2`.`profile_name` AND `r3`.`attribute` = 'Mikrotik-Rate-Limit' LEFT JOIN `radgroupreply` `r4` ON `r4`.`groupname` = `p2`.`profile_name` AND `r4`.`attribute` = 'Mikrotik-Address-List' LEFT JOIN `radgroupreply` `r5` ON `r5`.`groupname` = `p3`.`profile_name` AND `r5`.`attribute` = 'Mikrotik-Rate-Limit' LEFT JOIN `radgroupreply` `r6` ON `r6`.`groupname` = `p3`.`profile_name` AND `r6`.`attribute` = 'Mikrotik-Address-List' LEFT JOIN `radgroupreply` `r7` ON `r7`.`groupname` = `p`.`profile_name` AND `r7`.`attribute` = 'Mikrotik-Rate-Limit' LEFT JOIN `radgroupreply` `r8` ON `r8`.`groupname` = `p`.`profile_name` AND `r8`.`attribute` = 'Mikrotik-Address-List' LEFT JOIN `card_users` ON `card_users`.`id` = `radcheck`.`id_card` LEFT JOIN `radreply` as `radip` ON `radip`.`username` = `r9`.`username` AND `radip`.`attribute`='Framed-IP-Address' LEFT JOIN `radcheck` as `radmac` ON `radmac`.`username` = `r9`.`username` AND `radmac`.`attribute`='Calling-Station-Id' LEFT JOIN `radcheck` as `radcount` ON `radcount`.`username` = `r9`.`username` AND `radcount`.`attribute`='Simultaneous-Use' LEFT JOIN `radcheck` as `radexp` ON `radexp`.`username` = `r9`.`username` AND `radexp`.`attribute`='Expiration' WHERE ( radacct .AcctStopTime IS NULL OR radacct.AcctStopTime = '0000-00-00 00:00:00') GROUP BY `radacct`.`username` When remove this from query it speed up 60% LEFT JOIN (SELECT SUM(`radacct`.`acctinputoctets`) as `up_today`, SUM(`radacct`.`acctoutputoctets`) as `down_today`, SUM(`radacct`.`acctsessiontime`) as `daily_time`, `radacct`.`username` FROM `radacct` WHERE DATE_FORMAT(STR_TO_DATE(`acctstarttime`,'%Y-%m-%d %H:%i:%s'),'%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d') GROUP BY `username`) as `rad2` ON (`rad2`.`username` = `r9`.`username`) I have index for all this tables so what is my problem ? Note : I have pc have cpu core i 5 ram 4 giga this image for explain my table
How convert rows to columns(SQL)?
I want to do this: Desired Output but I actually have this: Current Output this is my sql code: enter code here SELECT `a`.`itemId` AS itemId, `a`.`donationId` AS `donationId`, `a`.`typeId` AS `typeId`, `a`.`currencyId` AS `currencyId`, `a`.memberId AS memberId, `a`.amount_total AS amount_total, a.ref AS ref, a.ref_bank AS ref_bank, `a`.`hidden` AS `hidden`, a.code AS code, concat( `b`.`first_name`, ' ', `b`.`last_name` ) AS member_name, `c`.currencyCode AS currencyCode, `f`.`name` AS `payment_name`, e.itemEnvelopId, e.itemId AS itemIdP, e.accountId, e.amount, e.hidden as envelopHidden, g.NAME, g.new_number FROM ai_donation_items `a` LEFT JOIN ai_church_members `b` ON a.memberId = b.memberId LEFT JOIN ai_currency `c` ON a.currencyId = c.currencyId LEFT JOIN ai_payment_types `f` ON a.typeId = f.typeId LEFT JOIN ai_donation_envelops_item as e on a.itemId = e.itemId LEFT JOIN ai_accounts AS g ON e.accountId = g.accountId WHERE `a`.`hidden` = 0 AND e.hidden = 0 and a.donationId = 1
MySQL - Invalid use of group function with SUM
I'm getting the error message '#1111 - Invalid use of group function' with the following query and I'm not entirely sure why. I originally had each of the three components of the SUM as individual views (you can see the remnants of that setup in the JOIN list), but it was taking too long to run that view due to not being able to use indexes in joining view. SELECT `VehicleClaim`.`id` AS `Vehicle_claim_id`, `VehicleClaim`.`Vehicle_registration_number`, `Claim`.`id` AS `claim_id`, `Claim`.`created` AS `claim_created`, DATE_FORMAT(`Claim`.`created`, '%b') AS `claim_created_month`, `ClaimSubtype`.`name` AS `claim_subtype`, `Vendor`.`name` as `vendor_name`, IF(`VehicleClaim`.`id` IS NOT NULL, IF(`VehicleClaimUpdate`.`id` IS NOT NULL, `VehicleClaimUpdateStatus`.`status`, `ClaimStatus`.`status`), IF(`ClaimUpdate`.`id` IS NOT NULL, `ClaimUpdateStatus`.`status`, `ClaimStatus`.`status`) ) AS `status`, IF(`VehicleClaimUpdate`.`id` IS NOT NULL, `VehicleClaimUpdate`.`result`, IF(`ClaimUpdate`.`id` IS NOT NULL, `ClaimUpdate`.`result`, NULL) ) AS `result`, SUM( (IF((`VehicleClaimUpdate`.`conceded_labour_cost` is not null), `VehicleClaimUpdate`.`conceded_labour_cost`, IF((`ClaimUpdate`.`id` is not null), `ClaimUpdate`.`conceded_labour_cost`, IF((`Claim`.`repair_order_id` is not null), IF((`RepairOrder`.`cost` is not null), `RepairOrder`.`cost`, SUM((`RepairOrder`.`removal_refit_hours` * `RepairOrderHourlyRate`.`rate`)) ), IF((`VehicleClaim`.`id` is not null),SUM((`VehicleClaim`.`work_hours` * `VehicleClaimHourlyRate`.`rate`)),0) ) ) )) + (IF((`VehicleClaimUpdate`.`conceded_material_cost` is not null), `VehicleClaimUpdate`.`conceded_material_cost`, IF((`ClaimUpdate`.`id` is not null), `ClaimUpdate`.`conceded_material_cost`, IF((`ClaimMaterial`.`id` is not null),SUM((((`ClaimMaterial`.`unit_cost` * `ClaimMaterial`.`quantity`) * `ClaimMaterial`.`percentage_claimed`) / 100)),0) ) )) + (IF(`VehicleClaimUpdate`.`conceded_freight_cost` IS NOT NULL, `VehicleClaimUpdate`.`conceded_freight_cost`, IF(`ClaimUpdate`.`id` IS NOT NULL, `ClaimUpdate`.`conceded_freight_cost`, IF(`ClaimFreight`.`id` IS NOT NULL, `ClaimFreight`.`cost`, 0) ) )) ) AS `total_cost`, `User`.`id` AS `user_id`, `User`.`username`, `Client`.`id` AS `client_id` FROM `Vehicle_claims` AS `VehicleClaim` RIGHT JOIN `claims` AS `Claim` ON (`Claim`.`id` = `VehicleClaim`.`claim_id`) LEFT JOIN `claim_materials` AS `ClaimMaterial` ON (`ClaimMaterial`.`claim_id` = `Claim`.`id`) LEFT JOIN `claim_freight` AS `ClaimFreight` ON (`ClaimFreight`.`claim_id` = `Claim`.`id`) LEFT JOIN `claim_subtypes` AS `ClaimSubtype` ON (`ClaimSubtype`.`id` = `Claim`.`claim_subtype_id`) LEFT JOIN `repair_orders` AS `RepairOrder` ON (`RepairOrder`.`id` = `Claim`.`repair_order_id`) LEFT JOIN `hourly_rates` AS `RepairOrderHourlyRate` ON (`RepairOrderHourlyRate`.`id` = `RepairOrder`.`hourly_rate_id`) LEFT JOIN `hourly_rates` AS `VehicleClaimHourlyRate` ON (`VehicleClaimHourlyRate`.`id` = `VehicleClaim`.`hourly_rate_id`) -- LEFT JOIN `view_final_material_cost` AS `FinalMaterialCost` ON (`FinalMaterialCost`.`claim_id` = `Claim`.`id` AND `FinalMaterialCost`.`Vehicle_claim_id` = `VehicleClaim`.`id`) -- LEFT JOIN `view_final_freight_cost` AS `FinalFreightCost` ON (`FinalFreightCost`.`claim_id` = `Claim`.`id` AND `FinalFreightCost`.`Vehicle_claim_id` = `VehicleClaim`.`id`) -- LEFT JOIN `view_final_labour_cost` AS `FinalLabourCost` ON (`FinalLabourCost`.`claim_id` = `Claim`.`id` AND `FinalLabourCost`.`Vehicle_claim_id` = `VehicleClaim`.`id`) LEFT JOIN `vendor_contacts` AS `VendorContact` ON (`VendorContact`.`id` = `Claim`.`vendor_contact_id`) LEFT JOIN `vendors` AS `Vendor` ON (`Vendor`.`id` = `VendorContact`.`vendor_id`) LEFT JOIN `users` AS `User` ON (`User`.`id` = `Claim`.`user_id`) LEFT JOIN `clients` AS `Client` ON (`Client`.`id` = `Claim`.`client_id`) LEFT JOIN `claim_statuses` AS `ClaimStatus` ON (`ClaimStatus`.`id` = `Claim`.`claim_status_id`) LEFT JOIN `claim_updates` AS `ClaimUpdate` ON (`ClaimUpdate`.`id` = `Claim`.`claim_update_id`) left join `claim_statuses` AS `ClaimUpdateStatus` on (`ClaimUpdateStatus`.`id` = `ClaimUpdate`.`claim_status_id`) left join `claim_statuses` AS `VehicleClaimStatus` on (`ClaimStatus`.`id` = `VehicleClaim`.`claim_status_id`) LEFT JOIN `claim_updates` AS `VehicleClaimUpdate` ON (`VehicleClaimUpdate`.`id` = `VehicleClaim`.`claim_update_id`) left join `claim_statuses` AS `VehicleClaimUpdateStatus` on (`VehicleClaimUpdateStatus`.`id` = `VehicleClaimUpdate`.`claim_status_id`) WHERE YEAR(`Claim`.`created`) = YEAR(CURDATE()) GROUP BY `VehicleClaim`.`id`
SQL if statement for null values in INNER JOINs
I'm writing a stored procedure that looks something like this: SELECT Positions.PositionId ,Positions.Title ,Positions.Location ,Positions.Description ,Positions.MaximumSalary ,PositionsDepartments.Description Department ,PositionsSubDepartments.Description Subdepartment ,PositionsDepartments.DepartmentId DepartmentId ,PositionsSubDepartments.SubDepartmentId SubdepartmentId ,#TheRole TheRole ,#Essentials Essentials ,#Desirable Desirable ,Positions.Published ,Positions.LastUpdatedDate ,PositionsStatus.Description Status FROM Positions WITH (NOLOCK) INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId INNER JOIN PositionsSubDepartments ON Positions.SubDepartmentId = PositionsSubDepartments.SubDepartmentId INNER JOIN PositionsDepartments ON PositionsSubDepartments.DepartmentId = PositionsDepartments.DepartmentId WHERE Positions.PositionId = #PositionId BUT the Positions.SubDepartmentId could now be null - which means I don't get all the data back that I'm expecting. I've tried this but get a load of duplicate data back: SELECT Positions.PositionId ,Positions.Title ,Positions.Location ,Positions.Description ,Positions.MaximumSalary ,PositionsDepartments.Description Department ,PositionsSubDepartments.Description Subdepartment ,PositionsDepartments.DepartmentId DepartmentId ,PositionsSubDepartments.SubDepartmentId SubdepartmentId ,#TheRole TheRole ,#Essentials Essentials ,#Desirable Desirable ,Positions.Published, Positions.LastUpdatedDate ,PositionsStatus.Description Status FROM Positions WITH (NOLOCK) INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId INNER JOIN PositionsSubDepartments ON Positions.SubDepartmentId = PositionsSubDepartments.SubDepartmentId OR ( Positions.SubDepartmentId IS NULL) INNER JOIN PositionsDepartments ON PositionsSubDepartments.DepartmentId = PositionsDepartments.DepartmentId WHERE Positions.PositionId = #PositionId What am I doing wrong?
You need to use a left join when an entry could be null SELECT Positions.[PositionId] ,Positions.[Title] ,Positions.[Location] ,Positions.[Description] ,Positions.[MaximumSalary] ,PositionsDepartments.[Description] Department ,PositionsSubDepartments.[Description] Subdepartment ,PositionsDepartments.[DepartmentId] DepartmentId ,PositionsSubDepartments.[SubDepartmentId] SubdepartmentId ,#TheRole TheRole ,#Essentials Essentials ,#Desirable Desirable ,Positions.[Published] ,Positions.[LastUpdatedDate] ,PositionsStatus.[Description] Status FROM Positions WITH (NOLOCK) INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId LEFT JOIN PositionsSubDepartments ON Positions.SubDepartmentId = PositionsSubDepartments.SubDepartmentId LEFT JOIN PositionsDepartments ON PositionsSubDepartments.DepartmentId = PositionsDepartments.DepartmentId WHERE Positions.PositionId = #PositionId You might also find the following useful: http://www.tutorialspoint.com/sql/sql-left-joins.htm
select Positions.PositionId, Positions.Title, Positions.Location,Positions.Description,Positions.MaximumSalary, PositionsDepartments.Description Department, PositionsSubDepartments.Description Subdepartment, PositionsDepartments.DepartmentId DepartmentId, PositionsSubDepartments.SubDepartmentId SubdepartmentId, #TheRole TheRole, #Essentials Essentials, #Desirable Desirable, Positions.Published, Positions.LastUpdatedDate, PositionsStatus.Description Status FROM Positions WITH (NOLOCK) INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId LEFT JOIN PositionsSubDepartments ON Positions.SubDepartmentId = PositionsSubDepartments.SubDepartmentId LEFT JOIN PositionsDepartments ON PositionsSubDepartments.DepartmentId = PositionsDepartments.DepartmentId WHERE Positions.PositionId = #PositionId
Fixed it - thanks for your help: select Positions.PositionId, Positions.Title, Positions.Location, Positions.Description, Positions.MaximumSalary, Positions.DepartmentId, Positions.SubDepartmentId, PositionsDepartments.Description Department, PositionsSubDepartments.Description Subdepartment, PositionsSubDepartments.SubDepartmentId SubdepartmentId, #TheRole TheRole, #Essentials Essentials, #Desirable Desirable, Positions.Published, Positions.LastUpdatedDate, PositionsStatus.Description Status FROM Positions WITH (NOLOCK) INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId LEFT JOIN PositionsSubDepartments ON PositionsSubDepartments.SubDepartmentId = Positions.SubDepartmentId OR (Positions.SubDepartmentId IS NULL AND PositionsSubDepartments.SubDepartmentId IS NULL) LEFT JOIN PositionsDepartments ON Positions.DepartmentId = PositionsDepartments.DepartmentId WHERE Positions.PositionId = #PositionId
Improve query performance from many Master table
I have a query. I have created index for all joined key, pre-filter the master table and choose specific rows to select, but it still take long time to show(sometimes it hangs). What should We do to improve the performance? SELECT * FROM t_responden a INNER JOIN t_kepemilikan_tik b ON a.res_id = b.res_id INNER JOIN t_televisi c ON a.res_id = c.res_id INNER JOIN t_telepon_hp d ON a.res_id = d.res_id INNER JOIN t_radio e ON a.res_id = e.res_id INNER JOIN t_media_cetak f ON a.res_id = f.res_id INNER JOIN t_internet g ON a.res_id = g.res_id LEFT JOIN t_mst_pendidikan n ON a.res_pendidikan_kk = n.kd_pendidikan LEFT JOIN t_mst_pendidikan o ON a.res_pendidikan = o.kd_pendidikan LEFT JOIN t_mst_penghasilan p ON a.res_penghasilan = p.kd_penghasilan LEFT JOIN t_mst_aksesibilitas q ON a.res_aksesibilitas = q.kd_akses LEFT JOIN t_mst_mobilitas r ON a.res_mobilitas = r.kd_mobilitas LEFT JOIN t_mst_pekerjaan s ON a.res_pekerjaan = s.kode LEFT JOIN t_mst_pengeluaran t ON a.res_pengeluaran = t.kode INNER JOIN t_pernyataan h ON a.res_id = h.res_id INNER JOIN (SELECT * FROM t_mst_prop WHERE kode IN ( '3200', '1600', '1800', '3600' )) i ON a.res_propinsi = i.kode INNER JOIN (SELECT * FROM t_mst_kabkota WHERE kode_prop IN ( '3200', '1600', '1800', '3600' )) j ON ( a.res_kabkota = j.kode AND a.res_propinsi = j.kode_prop ) INNER JOIN (SELECT * FROM t_mst_kec WHERE kode_prop IN ( '3200', '1600', '1800', '3600' )) k ON ( a.res_kecamatan = k.kode AND a.res_kabkota = k.kode_kabkota AND a.res_propinsi = k.kode_prop ) INNER JOIN (SELECT * FROM t_mst_desa WHERE kode_prop IN ( '3200', '1600', '1800', '3600' ))l ON ( a.res_keldesa = l.kode AND a.res_kabkota = l.kode_kabkota AND a.res_propinsi = l.kode_prop AND l.kode_kec = a.res_kecamatan ) WHERE a.res_tahunsurvei = 2013 AND res_propinsi IN ( '3200', '1600', '1800', '3600' ) ORDER BY 1
SELECT STRAIGHT_JOIN * FROM t_responden a INNER JOIN t_kepemilikan_tik b ON a.res_id = b.res_id INNER JOIN t_televisi c ON a.res_id = c.res_id INNER JOIN t_telepon_hp d ON a.res_id = d.res_id INNER JOIN t_radio e ON a.res_id = e.res_id INNER JOIN t_media_cetak f ON a.res_id = f.res_id INNER JOIN t_internet g ON a.res_id = g.res_id LEFT JOIN t_mst_pendidikan n ON a.res_pendidikan_kk = n.kd_pendidikan LEFT JOIN t_mst_pendidikan o ON a.res_pendidikan = o.kd_pendidikan LEFT JOIN t_mst_penghasilan p ON a.res_penghasilan = p.kd_penghasilan LEFT JOIN t_mst_aksesibilitas q ON a.res_aksesibilitas = q.kd_akses LEFT JOIN t_mst_mobilitas r ON a.res_mobilitas = r.kd_mobilitas LEFT JOIN t_mst_pekerjaan s ON a.res_pekerjaan = s.kode LEFT JOIN t_mst_pengeluaran t ON a.res_pengeluaran = t.kode INNER JOIN t_pernyataan h ON a.res_id = h.res_id INNER JOIN t_mst_prop i ON a.res_propinsi = i.kode INNER JOIN t_mst_kabkota j ON a.res_propinsi = j.kode_prop AND a.res_kabkota = j.kode INNER JOIN t_mst_kec k ON a.res_propinsi = k.kode_prop AND a.res_kecamatan = k.kode AND a.res_kabkota = k.kode_kabkota INNER JOIN t_mst_desa l ON a.res_propinsi = l.kode_prop AND a.res_keldesa = l.kode AND a.res_kabkota = l.kode_kabkota AND a.res_kecamatan = l.kode_kec WHERE a.res_tahunsurvei = 2013 AND a.res_propinsi IN ( '3200', '1600', '1800', '3600' ) ORDER BY 1 You should have an index on your t_responden table ON ( res_tahunsurvei, res_propinsi) to match your where qualification criteria. Additionally, all your inner joins to the other tables where you are applying the IN via sub-selects is killing you. You are already limiting on the "kode"s in the where, so if you apply that as your join you should be good. Additionally, since all the other tables appear to be more "lookup", I've added "STRAIGHT_JOIN" to tell MySQL to query in the order the tables you have listed