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

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.

Related

How to update multiple table using INNER JOIN and multiple SELECT

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'

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

Show rows with SUM of two columns with subqueries and multiple JOINS

Hello I'm about to explode.. I have been trying for hours now getting this to work. I have found different solutions for others and tried to rewrite it so it fits to my script but it just wont work as it should.
With reference from Barmar to this post: Join tables with SUM issue in MYSQL
I have got a little way forward but I can't get it to print out what it should.
I have tried a lot of variant and moved around the JOINS etc. but without any luck. This is the query that gets nearest my wanted result:
SELECT
qs.statistic_ref_id,
qs.question_id,
SUM(qs.correct_count) AS count_correct,
qs2.total_count_2 AS total_count,
sr.user_id,
sr.quiz_id,
qq.title AS ny_titel,
qq.category_id,
SUBSTRING(qq.title,1,4) AS get_type_number,
pl.points
FROM pro_quiz_statistic AS qs
JOIN pro_quiz_statistic_ref sr ON sr.statistic_ref_id = qs.statistic_ref_id
JOIN pro_quiz_question qq ON qq.id = qs.question_id
JOIN user_points_log pl ON pl.quiz_id = sr.quiz_id AND pl.user_id = '$user_id'
JOIN ( SELECT
qs3.statistic_ref_id,
qs3.question_id,
SUM(qs3.correct_count + qs3.incorrect_count) AS total_count_2,
sr3.user_id,
sr3.quiz_id,
qq3.title AS ny_titel_2,
qq3.category_id,
SUBSTRING(qq3.title,1,4) AS get_type_number_2,
pl3.points
FROM pro_quiz_statistic AS qs3
JOIN pro_quiz_statistic_ref sr3 ON sr3.statistic_ref_id = qs3.statistic_ref_id
JOIN pro_quiz_question qq3 ON qq3.id = qs3.question_id
JOIN user_points_log pl3 ON pl3.quiz_id = sr3.quiz_id AND pl3.user_id = '$user_id'
WHERE sr3.user_id = '$user_id' AND
qq3.category_id = '3'
GROUP BY get_type_number_2 ORDER BY qs3.question_id
) qs2 ON qs2.statistic_ref_id = sr.statistic_ref_id
WHERE sr.user_id = '$user_id' AND
qq.category_id = '3'
GROUP BY get_type_number ORDER BY qs.question_id
You can see the outcome of this result in this picture (to the right):
whats_printing.jpg
The two first tables is pictures of the queries separately and is what it should print out. Just in one query.
I have tried with these two subqueries:
SELECT
qs.statistic_ref_id,
qs.question_id,
qs2.correct_count AS count_correct,
qs3.total_count_2 AS total_count,
sr.user_id,
sr.quiz_id,
qq.category_id,
SUBSTRING(qq.title,1,4) AS get_type_number,
pl.points
FROM pro_quiz_statistic AS qs
JOIN pro_quiz_statistic_ref sr ON sr.statistic_ref_id = qs.statistic_ref_id
JOIN pro_quiz_question qq ON qq.id = qs.question_id
JOIN user_points_log pl ON pl.quiz_id = sr.quiz_id AND pl.user_id = '$user_id'
JOIN (
SELECT
qs2.statistic_ref_id,
qs2.question_id,
SUM(qs2.correct_count) AS count_correct_2,
sr2.user_id,
sr2.quiz_id,
qq2.category_id,
SUBSTRING(qq2.title,1,4) AS get_type_number_2,
pl2.points
FROM pro_quiz_statistic AS qs2
JOIN pro_quiz_statistic_ref sr2 ON sr2.statistic_ref_id = qs2.statistic_ref_id
JOIN pro_quiz_question qq2 ON qq2.id = qs2.question_id
JOIN user_points_log pl2 ON pl2.quiz_id = sr2.quiz_id AND pl2.user_id = '$user_id'
WHERE sr2.user_id = '$user_id' AND
qq2.category_id = '3'
GROUP BY get_type_number_2
ORDER BY qs2.question_id
) qs2 ON qs2.statistic_ref_id = qs.statistic_ref_id
JOIN ( SELECT
qs3.statistic_ref_id,
qs3.question_id,
SUM(qs3.correct_count + qs3.incorrect_count) AS total_count_2,
sr3.user_id,
sr3.quiz_id,
qq3.category_id,
SUBSTRING(qq3.title,1,4) AS get_type_number_3,
pl3.points
FROM pro_quiz_statistic AS qs3
JOIN pro_quiz_statistic_ref sr3 ON sr3.statistic_ref_id = qs3.statistic_ref_id
JOIN pro_quiz_question qq3 ON qq3.id = qs3.question_id
JOIN user_points_log pl3 ON pl3.quiz_id = sr3.quiz_id AND pl3.user_id = '$user_id'
WHERE sr3.user_id = '$user_id' AND
qq3.category_id = '3'
GROUP BY get_type_number_3
ORDER BY qs3.question_id
) qs3 ON qs3.statistic_ref_id = qs.statistic_ref_id
WHERE sr.user_id = '$user_id' AND
qq.category_id = '3'
GROUP BY get_type_number
ORDER BY qs.question_id
but then it's not printing anything. This works:
SELECT
qs.statistic_ref_id,
qs.question_id,
SUM(qs.correct_count) AS count_correct,
sr.user_id,
sr.quiz_id,
qq.title AS ny_titel,
qq.category_id,
SUBSTRING(qq.title,1,4) AS get_type_number,
pl.points
FROM pro_quiz_statistic AS qs
JOIN pro_quiz_statistic_ref sr ON sr.statistic_ref_id = qs.statistic_ref_id
JOIN pro_quiz_question qq ON qq.id = qs.question_id
JOIN user_points_log pl ON pl.quiz_id = sr.quiz_id AND pl.user_id = '$user_id'
WHERE sr.user_id = '$user_id' AND
qq.category_id = '3'
GROUP BY get_type_number ORDER BY qs.question_id
And also this (if I run them separately):
SELECT
qs.statistic_ref_id,
qs.question_id,
SUM(qs.correct_count + qs.incorrect_count) AS count_correct,
sr.user_id,
sr.quiz_id,
qq.title AS ny_titel,
qq.category_id,
SUBSTRING(qq.title,1,4) AS get_type_number,
pl.points
FROM pro_quiz_statistic AS qs
JOIN pro_quiz_statistic_ref sr ON sr.statistic_ref_id = qs.statistic_ref_id
JOIN pro_quiz_question qq ON qq.id = qs.question_id
JOIN user_points_log pl ON pl.quiz_id = sr.quiz_id AND pl.user_id = '$user_id'
WHERE sr.user_id = '$user_id' AND
qq.category_id = '3'
GROUP BY get_type_number ORDER BY qs.question_id
But how can I combine those two to one query?

How to create codeigniter query from below sql query?

I've a query like this which is working fine but I want to create a pure CI query from this. I'm new in CI so can anyone help me to figure out how this can be done or suggest me a reference website or link from where i can get help. Thanks
SELECT
user_des,
IFNULL((sent),0) as sent,
IFNULL((viewed),0) as viewed,
CONCAT(IFNULL(fname_usr,user_des),' ',lname_usr,user_des) as fullname,
IFNULL(sum(duration),0) as totalviewtime,
IFNULL((totalviews),0) as views,
IFNULL(sum(sharedcount),0) as shares,
IFNULL(sum(shared),0) as shared
FROM dem_senddemo
INNER JOIN
(SELECT * FROM dem_demos WHERE id_dem IN (746,943,748) AND customer_dem = '1') as demosfiltered
ON demo_des = id_dem
LEFT JOIN
(
(
Select senddemo_wis, sum(duration) as duration, max(datereceived_wis) as datereceived_wis
FROM
(
select senddemo_wis, invited_wis, sum(IFNULL(duration_fea,0) * IFNULL(percentviewed_wis,0)) as duration, max(datereceived_wis) as datereceived_wis
FROM (sta_views
LEFT JOIN sta_featureswisitavisits as s ON visit_fvi = id_vis
LEFT JOIN
(
(SELECT shortvideovid_fea as videoid_fea, shortvideoduration_fea as duration_fea
FROM dem_features
where shortvideoduration_fea > 0)
UNION
(SELECT longvideovid_fea as videoid_fea, longvideoduration_fea as duration_fea
FROM dem_features
where longvideoduration_fea > 0)
) as x
ON videoid_fea = showedvideo_fvi)
LEFT JOIN
sta_wistia as w ON invited_fvi = invited_wis AND s.showedvideo_fvi = w.mediaid_wis AND wistia_vis = email_wis
WHERE countvisit_wis <> 'N'
GROUP BY invited_wis
) as durfea
GROUP BY senddemo_wis
) UNION
(
SELECT senddemo_wis,sum(IFNULL(mainvideoduration_dem ,0) * IFNULL(percentviewed_wis,0)) as duration, max(datereceived_wis) as datereceived_wis
FROM sta_wistia as w
INNER JOIN
(select *, customer_dem as cuss FROM dem_demos) as demcorp ON demo_wis = id_dem AND mainmessagingvideovid_dem = w.mediaid_wis
LEFT JOIN sta_views ON email_wis = wistia_vis
WHERE customer_dem = 1 AND senddemo_wis > 0 AND countvisit_wis <> 'N'
GROUP BY senddemo_wis
)
) as c ON id_des = senddemo_wis
LEFT JOIN
(
SELECT user_des as user2_des, count(id_vis) as totalviews
FROM sta_views
LEFT JOIN dem_invited ON id_invited = invited_vis
LEFT JOIN dem_senddemo ON id_des = id_senddemo
WHERE NOT ISNULL(id_senddemo) AND countvisit_wis != 'N' AND createdon_des BETWEEN '2015-05-31 00:00:00' AND '2015-06-29 23:59:59' AND demo_des IN (746,943,748)
GROUP BY user_des
) as z ON user_des = user2_des
LEFT JOIN
(
SELECT user_des as user3_des, count(id_des) as sent
FROM dem_senddemo
LEFT JOIN dem_invited ON id_senddemo = id_des
WHERE createdon_des BETWEEN '2015-05-31 00:00:00' AND '2015-06-29 23:59:59' AND demo_des IN (746,943,748) AND first_invited = 'YES'
GROUP BY user_des
) as za ON user_des = user3_des
LEFT JOIN
(
SELECT user_des as user4_des, count(id_vis) as viewed
FROM sta_views LEFT JOIN dem_invited ON id_invited = invited_vis
LEFT JOIN dem_senddemo ON id_des = id_senddemo
WHERE NOT ISNULL(id_senddemo) AND countvisit_wis != 'N' AND createdon_des BETWEEN '2015-05-31 00:00:00' AND '2015-06-29 23:59:59' AND state = 'VIEWED'
AND first_invited = 'YES' AND demo_des IN (746,943,748)
GROUP BY user_des
) as zb ON user_des = user4_des
LEFT JOIN
(
SELECT id_senddemo as iddemdemos2, count(id_senddemo) as shared, allshares as sharedcount
FROM
(
SELECT id_senddemo, count(id_senddemo) as allshares
FROM dem_invited
LEFT JOIN dem_senddemo on id_senddemo = id_des
WHERE first_invited <> 'YES' AND demo_des IN (746,943,748)
GROUP BY id_senddemo
) as x
GROUP BY id_senddemo
) as zc ON iddemdemos2 = id_des
LEFT JOIN
sec_users ON user_des = id_usr
WHERE customer_dem = 1 AND createdon_des BETWEEN '2015-05-31 00:00:00' AND '2015-06-29 23:59:59'
GROUP BY user_des