How to update multiple table using INNER JOIN and multiple SELECT - mysql

I'm trying to update 2 tables using inner Join and setting values with 2 results from variables. I've finally succeeded to have it work for a SELECT.
I want to updates my tables having a long where clause. And set the result from a select query.
Code is fine with select I get my results :
SET #DefID = "5289";
SELECT pt1.ID, pt1.post_title, pt1.post_content, mt2.meta_value
FROM wp_posts AS pt1
INNER JOIN wp_postmeta AS mt1
ON ( pt1.ID = mt1.post_id )
INNER JOIN wp_postmeta AS mt2
ON ( pt1.ID = mt2.post_id )
INNER JOIN wp_postmeta AS mt3
ON ( pt1.ID = mt3.post_id )
WHERE
pt1.ID != #DefID
AND
pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND
mt1.meta_key = 'tourmaster-tour-date-avail'
AND
CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND
mt2.meta_key = '_cornerstone_data'
AND
mt3.meta_key = 'tourmaster-tour-duration'
AND
mt3.meta_value = '10'
AND
pt1.post_type = 'tour'
AND
pt1.post_status = 'publish'
ORDER BY mt1.meta_value ASC
But not working with UPDATE
SET #DefID = "myID";
SET #post_content = ( SELECT wp_posts_bak.post_content FROM wp_posts_bak WHERE wp_posts_bak.ID = #DefID );
SET #meta_value = ( SELECT wp_postmeta_bak.meta_value FROM wp_postmeta_bak WHERE wp_postmeta_bak.post_id = #DefID AND wp_postmeta_bak.meta_key = '_cornerstone_data');
UPDATE wp_posts_bak AS pt1, wp_postmeta_bak AS mt0
INNER JOIN wp_postmeta_bak AS mt1 ON pt1.ID = mt1.post_id
INNER JOIN wp_postmeta_bak AS mt2 ON pt1.ID = mt2.post_id
INNER JOIN wp_postmeta_bak AS mt3 ON pt1.ID = mt3.post_id
SET
pt1.post_content = #post_content,
mt0.meta_value = #meta_value
WHERE
pt1.ID != #DefID
AND
pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND
mt1.meta_key = 'tourmaster-tour-date-avail'
AND
CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND
mt2.meta_key = '_cornerstone_data'
AND
mt3.meta_key = 'tourmaster-tour-duration'
AND
mt3.meta_value = '10'
AND
pt1.post_type = 'tour'
AND
pt1.post_status = 'publish'
Got the following error : Unknown column 'pt1.ID' in 'on clause.

I finally found the reason of the problem. In the UPDATE I had to remove the 2 tables.
So the solution is :
SET #DefID = "5289";
SET #post_content = ( SELECT wp_posts_bak.post_content FROM wp_posts_bak WHERE wp_posts_bak.ID = #DefID );
SET #meta_value = ( SELECT wp_postmeta_bak.meta_value FROM wp_postmeta_bak WHERE wp_postmeta_bak.post_id = #DefID AND wp_postmeta_bak.meta_key = '_cornerstone_data');
UPDATE wp_posts_bak AS pt1
INNER JOIN wp_postmeta_bak AS mt1 ON pt1.ID = mt1.post_id
INNER JOIN wp_postmeta_bak AS mt2 ON pt1.ID = mt2.post_id
INNER JOIN wp_postmeta_bak AS mt3 ON pt1.ID = mt3.post_id
SET
pt1.post_content = #post_content,
mt2.meta_value = #meta_value
WHERE
pt1.ID != #DefID
AND
pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND
mt1.meta_key = 'tourmaster-tour-date-avail'
AND
CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND
mt2.meta_key = '_cornerstone_data'
AND
mt3.meta_key = 'tourmaster-tour-duration'
AND
mt3.meta_value = '10'
AND
pt1.post_type = 'tour'
AND
pt1.post_status = 'publish'

Related

alternative to nested select mysql

I am running a query at the moment, and I believe that that nest selected is creating a bottle neck, is there an alternative option that I could use?
This is my query,
SELECT post_id,
post_order,
post_parent,
post_recycle,
post_status,
post_ps_id,
post_v_id,
post_src,
post_sn_id,
post_qpc_id,
post_date_posted,
post_scheduled_local_datetime,
post_recycle_repeats,
post_recycle_expiry_date,
post_text,
post_v_title,
link_url,
link_preview_removed,
link_name,
link_description,
link_caption,
link_url_is_bitlink,
link_bitly_destination_url,
link_expanded_url,
link_initial_is_bitlink,
link_destination,
link_picture,
link_picture_size,
link_facebook_image,
link_facebook_title,
link_facebook_description,
link_facebook_caption,
link_twitter_card,
link_twitter_image,
link_twitter_title,
link_twitter_description,
pause_m_id,
qpca_evergreen_too_frequent,
sn_network,
qpc_name,
qpc_colour,
ps_m_id,
ps_filename,
ps_via,
ps_s3,
ps_width,
ps_height,
ps_gif,
video.*,
(
SELECT COUNT(*) FROM post post_inner
WHERE (post_inner.post_parent = post.post_parent)
AND post_inner.post_status = 'published'
)
AS total_repeats
FROM post
JOIN social_network ON sn_id = post_sn_id AND sn_status = 'active'
JOIN queue_post_cat ON qpc_id = post_qpc_id
LEFT JOIN queue_post_cat_account ON qpca_qpc_id = post_qpc_id AND qpca_sn_id = post_sn_id
LEFT JOIN link ON link_id = post_link_id
LEFT JOIN pause ON pause_m_id = qpc_m_id AND pause_qpc_id = post_qpc_id AND pause_sn_id = post_sn_id
LEFT JOIN photo_status ON ps_id = post_ps_id
LEFT JOIN video ON post_v_id = v_id AND v_transcoded = 1 LEFT JOIN facebook ON fb_db_id = sn_account_id AND sn_network = 'facebook'
WHERE post_status != 'now'
AND post_m_id = 1
AND qpca_sn_id IS NOT NULL
AND qpca_qpc_id IS NOT NULL
AND post_status = 'queue' AND (sn_network = 'facebook'
OR sn_network = 'instagram' OR sn_network = 'twitter')
AND qpc_m_id = 1 AND (fb_type IS NULL OR fb_type != 'profile') ORDER BY post_order ASC
I believe the bottle neck is happening here,
SELECT COUNT(*) FROM post post_inner
WHERE (post_inner.post_parent = post.post_parent)
AND post_inner.post_status = 'published'
which is select within the main select, is there something I could do that would run faster?
You can try with subquery:
select * from
(
SELECT post_id,
post_order,
post_parent,
post_recycle,
post_status,
post_ps_id,
post_v_id,
post_src,
post_sn_id,
post_qpc_id,
post_date_posted,
post_scheduled_local_datetime,
post_recycle_repeats,
post_recycle_expiry_date,
post_text,
post_v_title,
link_url,
link_preview_removed,
link_name,
link_description,
link_caption,
link_url_is_bitlink,
link_bitly_destination_url,
link_expanded_url,
link_initial_is_bitlink,
link_destination,
link_picture,
link_picture_size,
link_facebook_image,
link_facebook_title,
link_facebook_description,
link_facebook_caption,
link_twitter_card,
link_twitter_image,
link_twitter_title,
link_twitter_description,
pause_m_id,
qpca_evergreen_too_frequent,
sn_network,
qpc_name,
qpc_colour,
ps_m_id,
ps_filename,
ps_via,
ps_s3,
ps_width,
ps_height,
ps_gif,
video.*,
FROM post
JOIN social_network ON sn_id = post_sn_id AND sn_status = 'active'
JOIN queue_post_cat ON qpc_id = post_qpc_id
LEFT JOIN queue_post_cat_account ON qpca_qpc_id = post_qpc_id AND qpca_sn_id = post_sn_id
LEFT JOIN link ON link_id = post_link_id
LEFT JOIN pause ON pause_m_id = qpc_m_id AND pause_qpc_id = post_qpc_id AND pause_sn_id = post_sn_id
LEFT JOIN photo_status ON ps_id = post_ps_id
LEFT JOIN video ON post_v_id = v_id AND v_transcoded = 1 LEFT JOIN facebook ON fb_db_id = sn_account_id AND sn_network = 'facebook'
WHERE post_status != 'now'
AND post_m_id = 1
AND qpca_sn_id IS NOT NULL
AND qpca_qpc_id IS NOT NULL
AND post_status = 'queue' AND (sn_network = 'facebook'
OR sn_network = 'instagram' OR sn_network = 'twitter')
AND qpc_m_id = 1 AND (fb_type IS NULL OR fb_type != 'profile')) A
inner join
(
SELECT post_parent ,COUNT(*) FROM post where post_status = 'published' group by post_parent
) B on A.post_parent = B.post_parent
ORDER BY post_order ASC

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

Using one sub query result multiple times in the same mysql query

How can we use result set of one subquery multiple times in the same query
SELECT
(
SELECT
COUNT(joa.id)
FROM
game_applied joa
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) be ON joa.referred_by = be.id
) AS applicationcount,
(
SELECT
COUNT(joa.id)
FROM
game_applied joa
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bf ON joa.referred_by = bf.id
AND joa.admin_review = '3'
AND joa.rejection_reason = 'Admin rejected your game'
) AS admin_reject,
(
SELECT
COUNT(joa.id)
FROM
game_applied joa
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bg ON joa.referred_by = bg.id
AND joa. STATUS = '5'
AND joa.admin_review = '2'
) AS employer_reject,
(
SELECT
COUNT(joa.id)
FROM
game_applied joa
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bd ON joa.referred_by = bd.id
AND joa.admin_review = '1'
) AS admin_review,
(
SELECT
COUNT(joa.id)
FROM
game_applied joa
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bc ON joa.referred_by = bc.id
AND joa.admin_review = '5'
) AS accountmanager_review,
(
SELECT
COUNT(joa.id)
FROM
game_applied joa
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) ba ON joa.referred_by = ba.id
AND joa.admin_review = '6'
) AS rp_review,
(
SELECT
COUNT(joa.id)
FROM
game_applied joa
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = 1
) bh ON joa.referred_by = bh.id
AND joa.admin_review = '2'
AND (
joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa. STATUS = 3 || joa. STATUS = 4
)
) AS other_status
FROM
game_applied ja
JOIN user_user u ON u.id = ja.applied_recruiter_id
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bn ON ja.referred_by = bn.id
GROUP BY
applicationcount
How can we use result set of one subquery multiple times in the same query
the sub query used mulitple times in this query to a single use
(
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bn ON ja.referred_by = bn.id
Try this:
SELECT COUNT(joa.id) AS applicationcount,
SUM(joa.admin_review = '3' AND joa.rejection_reason = 'Admin Rejected your resume') AS admin_reject,
SUM(joa.STATUS = '5' AND joa.admin_review = '2') AS employer_reject,
SUM(joa.admin_review = '1') AS admin_review,
SUM(joa.admin_review = '5') AS accountmanager_review,
SUM(joa.admin_review = '6') AS rp_review,
SUM(joa.admin_review = '2' AND joa.STATUS != '5') AS other_status,
FROM game_refer_to_member jrmm
INNER JOIN game_refer jrr ON jrr.id = jrmm.rid AND jrr.referby_user_id = 2551
INNER JOIN game_applied joa ON jrmm.id = joa.referred_by
INNER JOIN user_user u ON u.id = joa.applied_recruiter_id
WHERE jrmm.STATUS = '1'
OK... I'll try to figure out what the query does first. I'll replace all instances of:
SELECT
COUNT(joa.id)
FROM
game_applied joa
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
with the phrase:
( SELECT count(*) FROM joa JOIN (subselect))
...for clarity.
I also removed the GROUP BY, since it is useless and/or misguided, unless you can explain why it is there.
I assume ja.applied_recruiter_id is a foreign key, which means...
JOIN user_user u ON u.id = ja.applied_recruiter_id
...always returns one row. Since no columns from user_user are actually selected, this join can be removed. Now, this part:
INNER JOIN (
SELECT
jrmm.id
FROM
game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bn ON ja.referred_by = bn.id
...it is unclear what this does. Since the subselect is the same as the one in the previous queries, it is unlikely that it would filter lines returned by the whole query. I'd say its only effect is to uselessly duplicate lines, which explains why there was a GROUP BY... So, off it goes.
We get:
SELECT
( SELECT count(*) FROM joa JOIN (subselect)) be ON joa.referred_by = be.id ) AS applicationcount,
( SELECT count(*) FROM joa JOIN (subselect)) bf ON joa.referred_by = bf.id
AND joa.admin_review = '3'
AND joa.rejection_reason = 'Admin rejected your game'
) AS admin_reject,
( SELECT count(*) FROM joa JOIN (subselect)) bg ON joa.referred_by = bg.id
AND joa. STATUS = '5'
AND joa.admin_review = '2'
) AS employer_reject,
( SELECT count(*) FROM joa JOIN (subselect)) bd ON joa.referred_by = bd.id
AND joa.admin_review = '1'
) AS admin_review,
( SELECT count(*) FROM joa JOIN (subselect)) bc ON joa.referred_by = bc.id
AND joa.admin_review = '5'
) AS accountmanager_review,
( SELECT count(*) FROM joa JOIN (subselect)) ba ON joa.referred_by = ba.id
AND joa.admin_review = '6'
) AS rp_review,
( SELECT count(*) FROM joa JOIN (subselect)) bh ON joa.referred_by = bh.id
AND joa.admin_review = '2'
AND (joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa. STATUS = 3 || joa. STATUS = 4)
) AS other_status
FROM
game_applied ja
...And, using the same logic as Sarhash, we simplify this into:
SELECT COUNT(joa.id) AS applicationcount,
SUM(joa.admin_review = '3' AND joa.rejection_reason = 'Admin Rejected your resume') AS admin_reject,
SUM(joa.STATUS = '5' AND joa.admin_review = '2') AS employer_reject,
SUM(joa.admin_review = '1') AS admin_review,
SUM(joa.admin_review = '5') AS accountmanager_review,
SUM(joa.admin_review = '6') AS rp_review,
SUM(joa.admin_review = '2' AND joa.STATUS != '5') AS other_status,
FROM game_refer_to_member jrmm
INNER JOIN game_refer jrr ON jrr.id = jrmm.rid
INNER JOIN game_applied joa ON jrmm.id = joa.referred_by
WHERE jrmm.STATUS = '1' AND jrr.referby_user_id = 2551
(which is the same, minus the useless join to USER and a cleanup in the WHERE, thank you Sarhash, you get all the credit).
I found a working solution using CREATE TEMPORARY TABLE. I'd suggest running two queries back to back in the same session. First, create some temporary tables from the subqueries you want to reference multiple times:
CREATE
TEMPORARY TABLE temp_table1
(SELECT COUNT(joa.id)
FROM game_applied);
CREATE
TEMPORARY TABLE new_table
(SELECT jrmm.id
FROM game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1');
After running a simple find-and-replace on your original query using these temporary table names, the new query would look like this:
SELECT
(SELECT *
FROM temp_table1 joa
INNER JOIN temp_table2 be ON joa.referred_by = be.id) AS applicationcount,
(SELECT *
FROM temp_table1 joa
INNER JOIN temp_table2 bf ON joa.referred_by = bf.id
AND joa.admin_review = '3'
AND joa.rejection_reason = 'Admin rejected your game') AS admin_reject,
(SELECT *
FROM temp_table1 joa
INNER JOIN temp_table2 bg ON joa.referred_by = bg.id
AND joa. STATUS = '5'
AND joa.admin_review = '2') AS employer_reject,
(SELECT *
FROM temp_table1 joa
INNER JOIN temp_table2 bd ON joa.referred_by = bd.id
AND joa.admin_review = '1') AS admin_review,
(SELECT *
FROM temp_table1 joa
INNER JOIN temp_table2 bc ON joa.referred_by = bc.id
AND joa.admin_review = '5') AS accountmanager_review,
(SELECT *
FROM temp_table1 joa
INNER JOIN temp_table2 ba ON joa.referred_by = ba.id
AND joa.admin_review = '6') AS rp_review,
(SELECT *
FROM temp_table1 joa
INNER JOIN
(SELECT jrmm.id
FROM game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = 1) bh ON joa.referred_by = bh.id
AND joa.admin_review = '2'
AND (joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa. STATUS = 3 || joa. STATUS = 4)) AS other_status
FROM game_applied ja
JOIN user_user u ON u.id = ja.applied_recruiter_id
INNER JOIN temp_table2 bn ON ja.referred_by = bn.id
GROUP BY applicationcount
I'm not guaranteeing that this query is without bugs, since I don't have your database and therefore cannot easily test it, but this at least outlines a decent strategy that I think should improve performance, and at very least makes the query about half the size.

How to optimize this complex MYSQL query?

Our website sometimes causes extreme server strain due to a complex MySQL query. The site actually goes down.
The webhoster warned that if we don't get this in order they will suspend our account.
Could someone give some pointers at which parts of this query eat the most resources?
Any suggestions on making this better?
SELECT SQL_CALC_FOUND_ROWS wp_s3mv0r_posts.ID
FROM wp_s3mv0r_posts
INNER JOIN wp_s3mv0r_term_relationships ON (wp_s3mv0r_posts.ID = wp_s3mv0r_term_relationships.object_id)
INNER JOIN wp_s3mv0r_postmeta ON ( wp_s3mv0r_posts.ID = wp_s3mv0r_postmeta.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt1 ON ( wp_s3mv0r_posts.ID = mt1.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt2 ON ( wp_s3mv0r_posts.ID = mt2.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt3 ON ( wp_s3mv0r_posts.ID = mt3.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt4 ON ( wp_s3mv0r_posts.ID = mt4.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt5 ON ( wp_s3mv0r_posts.ID = mt5.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt6 ON ( wp_s3mv0r_posts.ID = mt6.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt7 ON ( wp_s3mv0r_posts.ID = mt7.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt8 ON ( wp_s3mv0r_posts.ID = mt8.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt9 ON ( wp_s3mv0r_posts.ID = mt9.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt10 ON ( wp_s3mv0r_posts.ID = mt10.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt11 ON ( wp_s3mv0r_posts.ID = mt11.post_id )
INNER JOIN wp_s3mv0r_postmeta AS mt12 ON ( wp_s3mv0r_posts.ID = mt12.post_id )
WHERE 1=1 AND (
wp_s3mv0r_term_relationships.term_taxonomy_id IN (11,24,25)
) AND (
( wp_s3mv0r_postmeta.meta_key = 'acf_house_minprice' AND CAST(wp_s3mv0r_postmeta.meta_value AS SIGNED) BETWEEN '274990' AND '599990' )
AND
( mt1.meta_key = 'acf_house_minlotwidth' AND CAST(mt1.meta_value AS SIGNED) BETWEEN '16' AND '16' )
AND
( mt2.meta_key = 'acf_location_area' AND CAST(mt2.meta_value AS CHAR) IN ('South of river') )
AND
( mt3.meta_key = 'acf_house_bedroom' AND CAST(mt3.meta_value AS CHAR) = '4' )
AND
( mt4.meta_key = 'acf_house_studyroom' AND CAST(mt4.meta_value AS SIGNED) > '0' )
AND
( mt5.meta_key = 'acf_house_theaterroom' AND CAST(mt5.meta_value AS SIGNED) > '0' )
AND
( mt6.meta_key = 'acf_house_alfresco' AND CAST(mt6.meta_value AS SIGNED) > '0' )
AND
( mt7.meta_key = 'acf_house_activityroom' AND CAST(mt7.meta_value AS SIGNED) > '0' )
AND
( mt8.meta_key = 'acf_house_doublegarage' AND CAST(mt8.meta_value AS SIGNED) > '0' )
AND
( mt9.meta_key = 'acf_house_reargarage' AND CAST(mt9.meta_value AS SIGNED) > '0' )
AND
( mt10.meta_key = 'acf_house_islbeninkitchen' AND CAST(mt10.meta_value AS SIGNED) > '0' )
AND
( mt11.meta_key = 'acf_house_frontmasterbedroom' AND CAST(mt11.meta_value AS SIGNED) > '0' )
AND
( mt12.meta_key = 'acf_house_rearmaster' AND CAST(mt12.meta_value AS SIGNED) > '0' )
) AND wp_s3mv0r_posts.post_type = 'house' AND (wp_s3mv0r_posts.post_status = 'publish')
GROUP BY wp_s3mv0r_posts.ID
ORDER BY wp_s3mv0r_posts.post_date DESC
LIMIT 0, 10
How about this:
SELECT p.ID, count(*) AS 'PostCount'
FROM wp_s3mv0r_posts p INNER JOIN wp_s3mv0r_term_relationships r ON (p.ID = r.object_id)
INNER JOIN wp_s3mv0r_postmeta pm ON (p.ID = pm.post_id)
WHERE
r.term_taxonomy_id IN (11,24,25) AND p.post_type = 'house' AND p.post_status = 'publish' AND (
(pm.meta_key = 'acf_house_minprice' AND pm.meta_value BETWEEN '274990' AND '599990') OR
(pm.meta_key = 'acf_house_minlotwidth' AND pm.meta_value BETWEEN '16' AND '16') OR
(pm.meta_key = 'acf_location_area' AND pm.meta_value = 'South of river') OR
(pm.meta_key = 'acf_house_bedroom' AND pm.meta_value = '4') OR
(pm.meta_key IN ('acf_house_studyroom', 'acf_house_theaterroom', 'acf_house_alfresco', 'acf_house_activityroom',
'acf_house_doublegarage', 'acf_house_reargarage', 'acf_house_islbeninkitchen', 'acf_house_frontmasterbedroom',
'acf_house_rearmaster') AND pm.meta_value > '0'))
GROUP BY p.ID
ORDER BY p.post_date DESC
LIMIT 0, 10

optimize this query

ms sql server 2008
SELECT Action.*
FROM Mailing
INNER JOIN ActionCategoryMailingBunch
ON Mailing.MailingID = ActionCategoryMailingBunch.MailingID
INNER JOIN ActionCategory
ON ActionCategoryMailingBunch.ActionCategoryID =
ActionCategory.ActionCategoryID
INNER JOIN Action
ON ActionCategory.ActionCategoryID = Action.ActionCategoryID
WHERE ( Mailing.MailingID = 7 )
AND ( Mailing.MailingID NOT IN (SELECT MailingID
FROM MailingReport) )
AND ( Action.ActionID NOT IN (SELECT ActionID
FROM MailingReport) )
AND ( ActionCategoryMailingBunch.MailingBunchStatusID = 4 )
especially this block
(Mailing.MailingID NOT IN (SELECT MailingID FROM MailingReport))
AND (Action.ActionID NOT IN (SELECT ActionID FROM MailingReport))
Add the below code in the select statement
Left Join MailingReport MR on MR.ActionID = Mailing.MailingID
Add the below code in Where clause
(MR.ActionID is null)
Performance upgrade due to following block
(Mailing.MailingID NOT IN (SELECT MailingID FROM MailingReport))
Final Query
SELECT Action.*
FROM Mailing
INNER JOIN ActionCategoryMailingBunch
ON Mailing.MailingID = ActionCategoryMailingBunch.MailingID
INNER JOIN ActionCategory
ON ActionCategoryMailingBunch.ActionCategoryID =
ActionCategory.ActionCategoryID
INNER JOIN Action
ON ActionCategory.ActionCategoryID = Action.ActionCategoryID
Left Join MailingReport MR on MR.ActionID = Mailing.MailingID
WHERE ( Mailing.MailingID = 7 )
--AND ( Mailing.MailingID NOT IN (SELECT MailingID
-- FROM MailingReport) )
AND
(MR.ActionID is null)
AND ( Action.ActionID NOT IN (SELECT ActionID
FROM MailingReport) )
AND ( ActionCategoryMailingBunch.MailingBunchStatusID = 4 )
Similarly you can do for the second block
Performance due to second block
AND (Action.ActionID NOT IN (SELECT ActionID FROM MailingReport))
Final Query for both blocks
SELECT Action.*
FROM Mailing
INNER JOIN ActionCategoryMailingBunch
ON Mailing.MailingID = ActionCategoryMailingBunch.MailingID
INNER JOIN ActionCategory
ON ActionCategoryMailingBunch.ActionCategoryID =
ActionCategory.ActionCategoryID
INNER JOIN Action
ON ActionCategory.ActionCategoryID = Action.ActionCategoryID
Left Join MailingReport MR on MR.ActionID = Mailing.MailingID
Left Join MailingReport MRA on MRA.ActionID = Action.ActionID
WHERE ( Mailing.MailingID = 7 )
AND
(MR.ActionID is null)
AND
(MRA.ActionID is null)
AND ( ActionCategoryMailingBunch.MailingBunchStatusID = 4 )