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`
Related
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
I have some troubles to finish my Mysql Query to return me what I need to have. I am new to such long queries in MYSQL.
SELECT
lang_rel_a_id,
lang_rel_b_id,
lang_rel_id,
tla.text_lang_t AS atext,
lald.lang_data_lang_id AS laid,
lald.lang_data_position AS lapp,
lald.lang_data_font_weight AS lafw,
lald.lang_data_font_size AS lafs,
lald.lang_data_font_color AS lafc,
lald.lang_data_bg_color AS labg,
lasdf.funca AS lafunc,
lang_ship,
lbld.lang_data_lang_id AS lbid,
lbld.lang_data_position AS lbpp,
lbld.lang_data_font_weight AS lbfw,
lbld.lang_data_font_size AS lbfs,
lbld.lang_data_font_color AS lbfc,
lbld.lang_data_bg_color AS lbbg,
tlb.text_lang_t AS btext,
lbsdf.funcb AS lbfunc
FROM lang_relation
LEFT JOIN
(SELECT *, GROUP_CONCAT(text_func_t SEPARATOR ', ') AS funca
FROM synt_data_func
LEFT JOIN text_func ON text_func_id = synt_df_func
GROUP BY synt_df_lang_data
)
lasdf ON lang_rel_a_id = lasdf.synt_df_lang_data
LEFT JOIN lang_data lald ON lald.lang_data_id = lang_rel_a_id
LEFT JOIN text_lang tla ON lald.lang_data_lang_id = tla.text_lang_id
LEFT JOIN
(SELECT *, GROUP_CONCAT(text_func_t SEPARATOR ', ') AS funcb
FROM synt_data_func
LEFT JOIN text_func ON text_func_id = synt_df_func
GROUP BY synt_df_lang_data
)
lbsdf ON lang_rel_b_id = lbsdf.synt_df_lang_data
LEFT JOIN lang_data lbld ON lbld.lang_data_id = lang_rel_b_id
LEFT JOIN text_lang tlb ON lbld.lang_data_lang_id = tlb.text_lang_id
WHERE lang_rel_a_id < lang_rel_b_id
GROUP BY lang_rel_id
I have a relation of two languages in my lang_relation table. I need to query for each of them 2 subtables but the one of them is a relation table that contains the relation between the lang_data_id (= lang_rel_a_id OR lang_rel_b_id, = synt_df_lang_data) and text of the different language functions where multiple values are possible.
I do not understand why the group_concat in this subquery returns only one row. If I do only this query, I get all the results. But when I put it into this larger query, everything's fine but this.. is ..not.
My language_relation table
CREATE TABLE `lang_relation`
(
`lang_rel_id` int(11) NOT NULL,
`lang_rel_a_id` int(11) NOT NULL,
`lang_rel_b_id` int(11) NOT NULL,
`lang_ship` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The joined lang_data
CREATE TABLE `lang_data` (
`lang_data_id` int(11) NOT NULL,
`lang_data_pic_key` int(11) NOT NULL,
`lang_data_position` tinyint(1) NOT NULL,
`lang_data_lang_id` int(11) NOT NULL,
`lang_data_font_weight` tinyint(2) NOT NULL,
`lang_data_font_size` tinyint(2) NOT NULL,
`lang_data_font_color` tinyint(2) NOT NULL,
`lang_data_bg_color` tinyint(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
And the synt_data_func. The text_table is a simple 2-column-table with id + text.
CREATE TABLE `synt_data_func` (
`synt_df_id` int(11) NOT NULL,
`synt_df_lang_data` int(11) NOT NULL,
`synt_df_func` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
I tried different approachs. This seems to be the one that is the nearest of what I need. I don't know how many times I changed the GROUP BY clauses, I even tried to do the CONCAT_GROUP in the parent SELECT..
I even wonder if this is possible because the subqueries are going for 2 different IDs .. is this the problem?
Thanks for any hint in advance.
I finally got it. Maybe it will help somebody with a similar question. I changed my approach for this query.
SELECT
lrel.lang_rel_pic_key,
lrel.lang_rel_id,
langdata_a.lascore,
lasdf.func_a,
langdata_a.latext,
lasf.score_astyle,
SUM(lasf.score_astyle) + (langdata_a.lascore) AS atotal,
lang_ship,
langdata_b.lbtext,
langdata_b.lbscore,
lbsdf.func_b,
lbsf.bformat,
lbsf.score_bstyle,
SUM(lbsf.score_bstyle) + (langdata_b.lbscore) AS btotal
FROM lang_relation lrel
INNER JOIN
(
SELECT DISTINCT
lald.lang_data_id,
lafw.field_value AS lafweight,
lafs.field_value AS lafsize,
lafc.field_value AS laffc,
lafbg.field_value AS lafbg,
lapos.field_value AS laposa,
tla.text_lang_t AS latext,
SUM(lafw.field_value) + (lafs.field_value) + (lafc.field_value) + (lafbg.field_value) + (lapos.field_value) AS lascore
FROM lang_data lald
LEFT JOIN text_lang tla ON lald.lang_data_lang_id = tla.text_lang_id
LEFT JOIN `fields` lafw ON lald.lang_data_font_weight = lafw.field_id
LEFT JOIN `fields` lafs ON lald.lang_data_font_size = lafs.field_id
LEFT JOIN `fields` lafc ON lald.lang_data_font_color = lafc.field_id
LEFT JOIN `fields` lafbg ON lald.lang_data_bg_color = lafbg.field_id
LEFT JOIN `fields` lapos ON lald.lang_data_position = lapos.field_id
GROUP BY lald.lang_data_id
)
langdata_a ON langdata_a.lang_data_id = lrel.lang_rel_a_id
LEFT JOIN
(SELECT sdf.synt_df_lang_data, GROUP_CONCAT(latf.text_func_t) AS func_a
FROM synt_data_func sdf
INNER JOIN text_func latf ON latf.text_func_id = sdf.synt_df_func
GROUP BY sdf.synt_df_lang_data
)
lasdf ON lasdf.synt_df_lang_data = lrel.lang_rel_a_id
LEFT JOIN
(
SELECT sfb.synt_format_lang_data,
sfb.synt_format_fields_id,
GROUP_CONCAT(sfbf.field_text SEPARATOR ', ') AS aformat,
SUM(sfbf.field_value) AS score_astyle
FROM synt_format sfb
INNER JOIN `fields` sfbf ON sfbf.field_id = sfb.synt_format_fields_id
GROUP BY sfb.synt_format_lang_data
)
lasf ON lasf.synt_format_lang_data = lrel.lang_rel_a_id
INNER JOIN
(
SELECT DISTINCT
lbld.lang_data_id,
lbfw.field_value AS lbfweight,
lbfs.field_value AS lbfsize,
lbfc.field_value AS lbffc,
lbfbg.field_value AS lbfbg,
lbpos.field_value AS lbposa,
tlb.text_lang_t AS lbtext,
SUM(lbfw.field_value) + (lbfs.field_value) + (lbfc.field_value) + (lbfbg.field_value) + (lbpos.field_value) AS lbscore
FROM lang_data lbld
LEFT JOIN text_lang tlb ON lbld.lang_data_lang_id = tlb.text_lang_id
LEFT JOIN `fields` lbfw ON lbld.lang_data_font_weight = lbfw.field_id
LEFT JOIN `fields` lbfs ON lbld.lang_data_font_size = lbfs.field_id
LEFT JOIN `fields` lbfc ON lbld.lang_data_font_color = lbfc.field_id
LEFT JOIN `fields` lbfbg ON lbld.lang_data_bg_color = lbfbg.field_id
LEFT JOIN `fields` lbpos ON lbld.lang_data_position = lbpos.field_id
GROUP BY lbld.lang_data_id
)
langdata_b ON langdata_b.lang_data_id = lrel.lang_rel_b_id
LEFT JOIN
(SELECT sdfb.synt_df_lang_data, GROUP_CONCAT(lbtf.text_func_t) AS func_b
FROM synt_data_func sdfb
INNER JOIN text_func lbtf ON lbtf.text_func_id = sdfb.synt_df_func
GROUP BY sdfb.synt_df_lang_data
)
lbsdf ON lbsdf.synt_df_lang_data = lrel.lang_rel_b_id
LEFT JOIN
(
SELECT sfb.synt_format_lang_data,
sfb.synt_format_fields_id,
GROUP_CONCAT(sfbf.field_text SEPARATOR ', ') AS bformat,
SUM(sfbf.field_value) AS score_bstyle
FROM synt_format sfb
INNER JOIN `fields` sfbf ON sfbf.field_id = sfb.synt_format_fields_id
GROUP BY sfb.synt_format_lang_data
)
lbsf ON lbsf.synt_format_lang_data = lrel.lang_rel_b_id
GROUP BY lrel.lang_rel_id
Maybe a bit long, but output is exactly what was needed :-)
I have a principal requet with 2 requets in. I have a problem in my second nested query, I have a condition on id and if I made my request id = 10 takes a long time to execute, so if I replace it by id LIKE 10 my request execute in one second.
Here the request:
SELECT SQL_NO_CACHE contact_groupe.id_contact_groupe
FROM toto.contact_groupe
LEFT JOIN toto.`contact` AS `contact`
ON ((toto.contact_groupe.id_contact_groupe = toto.contact.id_contact_groupe))
LEFT JOIN toto.`project` AS `project`
ON ((toto.contact_groupe.id_contact_groupe = toto.project.id_contact_groupe)
AND ( toto.project.id_project
IN (
SELECT MAX(toto.project.id_project)
FROM toto.project
WHERE ( toto.contact_groupe.id_contact_groupe = toto.project.id_contact_groupe )
) ))
LEFT JOIN toto.`phase` AS `phase`
ON ((project.id_phase = toto.phase.id_phase))
LEFT JOIN sql_base.`user` AS `user_suivi`
ON ((toto.contact_groupe.id_user_suivi = user_suivi.id_user))
WHERE ( en_attente = '0' AND contact_groupe.id_contact_groupe
IN (
SELECT DISTINCT(contact_groupe.id_contact_groupe)
FROM toto.contact_groupe
LEFT JOIN toto.`contact` AS `contact`
ON ((toto.contact_groupe.id_contact_groupe = toto.contact.id_contact_groupe)
LEFT JOIN toto.`source_contact_groupe` AS `source_contact_groupe`
ON ((toto.contact_groupe.id_contact_groupe = toto.source_contact_groupe.id_contact_groupe))
LEFT JOIN toto.`project` AS `project`
ON ((toto.contact_groupe.id_contact_groupe = toto.project.id_contact_groupe))
LEFT JOIN toto.`remarque` AS `remarque`
ON ((toto.contact_groupe.id_contact_groupe = toto.remarque.id_contact_groupe))
LEFT JOIN toto.`project_type_construction_options` AS `project_type_construction_options`
ON ((project.id_project = toto.project_type_construction_options.id_project))
LEFT JOIN toto.`project_concurrent` AS `project_concurrent`
ON ((project.id_project = toto.project_concurrent.id_project))
LEFT JOIN toto.`telephone` AS `telephone`
ON ((contact.id_contact = toto.telephone.id_contact))
WHERE ( en_attente = '0' AND ( toto.project.id_project = '10' ) AND toto.contact_groupe.id_entreprise = '2' )
)
AND toto.contact_groupe.id_entreprise = '2' )
ORDER BY toto.contact_groupe.id_contact_groupe ASC
the line is the following problem toto.project.id_project = '10' and I don't understand why the time to execute request is so different between = and LIKE
Let's start with your subquery. Those 17 lines that you've written are functionally identical to this, so why not use this instead?
SELECT DISTINCT g.id_contact_groupe
FROM contact_groupe g
JOIN project p
ON p.id_contact_groupe = g.id_contact_groupe
WHERE g.en_attente = 0
AND p.id_project = 10
AND g.id_entreprise = 2
Hi i have trouble with this query
SELECT * FROM(
SELECT `b`.*,`owner`.firstname,`owner`.lastname,`owner`.email,
(
SELECT COUNT(`ps`.profile_id) FROM `profile` AS `ps`
LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id
WHERE `xbp`.brand_id = b.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL
) AS `salesrepTotal`,
(
SELECT GROUP_CONCAT(`ms`.firstname) FROM `profile` AS `ps`
LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id
LEFT JOIN `member` AS `ms`ON `ms`.member_id = `ps`.member_id
WHERE `xbp`.brand_id = `b`.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL
) AS `salesrep`,
(
SELECT COUNT(`s`.store_id) FROM `store` AS `s`
LEFT JOIN `xref_store_profile_brand` AS `xbs` ON `xbs`.store_id = `s`.store_id
WHERE `xbs`.brand_id = `b`.brand_id AND `xbs`.brand_id IS NOT NULL
) AS `storeTotal`,
(
SELECT GROUP_CONCAT(`s`.name) FROM `store` AS `s`
LEFT JOIN `xref_store_profile_brand` AS `xbs` ON `xbs`.store_id = `s`.store_id
WHERE `xbs`.brand_id = `b`.brand_id AND `xbs`.brand_id IS NOT NULL
) AS `store`
FROM `brand` AS `b`
LEFT JOIN
(
SELECT `m`.firstname,`m`.lastname,`m`.email,`xspb`.brand_id FROM `member` AS `m`
LEFT JOIN `profile` as `p` ON `p`.member_id = `m`.member_id AND `p`.role = 'designer' AND `p`.isPrimary = 1
LEFT JOIN `xref_store_profile_brand` AS `xspb` ON `xspb`.profile_id = `p`.profile_id AND `xspb`.store_id IS NULL
) AS `owner` ON `owner`.brand_id =`b`.brand_id
GROUP BY `b`.brand_id
) AS `final`
how can i convert this in to Zend_Db_Select object?
Th main problem is
this part
SELECT `b`.*,`owner`.firstname,`owner`.lastname,`owner`.email,
(
SELECT COUNT(`ps`.profile_id) FROM `profile` AS `ps`
LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id
WHERE `xbp`.brand_id = b.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL
) AS `salesrepTotal`,
You need to use Zend_Db_Expr objects in your query and array structures for select AS.
below is the solution you are looking for:
<?php
$db = Zend_Db_Table::getDefaultAdapter();
// inner query
$sqlSalesRepTotal = $db->select()
->from(array('ps' => 'profile'))
->joinLeft(array('xbp' => 'xref_store_profile_brand'), 'xbp.profile_id = ps.profile_id')
->where('xbp.brand_id = b.brand_id')
->where('ps.role = ?', 'salesrep')
->where('xbp.store_id IS NULL');
// main query
$sql = $db->select()
->from(array('b' => 'brand'), array(
// NOTE: have to add parentesis around the expression
'salesrepTotal' => new Zend_Db_Expr("($sqlSalesRepTotal)")
))
->where('....')
->group('brand_id');
// debug
var_dump($db->fetchAll($sql));
I have a query that JOINs some tables to get a list of products including prices, images, country etc.
"product_images" table can have zero or more images but only the default image should be returned. My problem is that in any case the query should return a result for the product even if there is no image in the "product_images" table for that particular product.
The first query example will return a row for each product but just return a random image:
SELECT `cp`.`category_id`, `p`.`id`, `p`.`master`, `p`.`status`, `p`.`sortorder`, `p`.`sku`, `p`.`stock`, `pd`.`name`, `pd`.`short_description`, `pd`.`description`, `pd`.`slug`, `pi`.`image`, `pi`.`path`
FROM `categories_products` AS `cp`
JOIN `products` AS `p` ON (`cp`.`product_id` = `p`.`id`)
JOIN `product_descriptions` AS `pd`
ON (`pd`.`product_id` = `p`.`id`)
LEFT JOIN `product_images` AS `pi`
ON (`pi`.`product_id` = `p`.`id`)
WHERE `cp`.`category_id` = 34
AND `pd`.`locale_id` = 1
AND `p`.`master` = '0'
AND `p`.`status` = '1'
AND `p`.`accessible` = '1'
AND `pd`.`status` = '1'
GROUP BY `p`.`id`
ORDER BY `p`.`sortorder`
Below query will return the default image. But if there is no image in "product_images" the row for that product will not be retrieved. The only difference here is this part: "AND pi.preset = 1"
SELECT `cp`.`category_id`, `p`.`id`, `p`.`master`, `p`.`status`, `p`.`sortorder`, `p`.`sku`, `p`.`stock`, `pd`.`name`, `pd`.`short_description`, `pd`.`description`, `pd`.`slug`, `pi`.`image`, `pi`.`path`
FROM `categories_products` AS `cp`
JOIN `products` AS `p` ON (`cp`.`product_id` = `p`.`id`)
JOIN `product_descriptions` AS `pd`
ON (`pd`.`product_id` = `p`.`id`)
LEFT JOIN `product_images` AS `pi`
ON (`pi`.`product_id` = `p`.`id`)
WHERE `cp`.`category_id` = 34
AND `pi`.`preset` = 1
AND `pd`.`locale_id` = 1
AND `p`.`master` = '0'
AND `p`.`status` = '1'
AND `p`.`accessible` = '1'
AND `pd`.`status` = '1'
GROUP BY `p`.`id`
ORDER BY `p`.`sortorder`
`pi`.`preset` = 1
in WHERE defeats your goal (your LEFT JOIN behaves like INNER ) . Move it to ON:
LEFT JOIN `product_images` AS `pi`
ON (`pi`.`product_id` = `p`.`id` AND `pi`.`preset` = 1)
You may prefer to use a subquery:
LEFT JOIN (SELECT * FROM product_images WHERE preset = 1) AS pi ON ...
Otherwise, the WHERE clause is applied to the entire query, and if there's no image, WHERE pi.preset=1 will reduce your search set to zero rows.