Convert MySQL view back into a query - mysql

Sorry if this has been answered elsewhere but I haven't been able to find the answer.
I created a view using HeidiSQL from a query I made. Due to a power outage my query was lost but the view was saved. Is there any way to convert the view back into a query? It is very ugly and hard to edit as a view.
The VIEW:
SELECT `c`.`assettag` AS `c_assetTag`,
`c`.`serialnumber` AS `c_serialNumber`,
`c`.`datepurchased` AS `c_datePurchased`,`c`.`status` AS `c_status`,
`c`.`dateretired` AS `c_dateRetired`,`c`.`loaner` AS `c_loaner`,
`c`.`school` AS `c_school`,`c`.`mac` AS `c_mac`,
`c`.`notes` AS `c_notes`,
`c`.`model` AS `c_model`,`c`.`location` AS `c_location`,
`c`.`lastlocationupdate` AS `c_lastLocationUpdate`,
`c`.`warrantyexpiration` AS `c_warrantyExpiration`,
`c`.`warrantyvoid` AS `c_warrantyVoid`,
`c`.`warrantyvoidnotes` AS `c_warrantyVoidNotes`,
`c`.`description` AS `c_description`,
`a`.`assignmentid` AS `a_assignmentID`,
`a`.`studentid` AS `a_studentID`,`a`.`grade` AS `a_grade`,
`a`.`gradyear` AS `a_gradYear`,`a`.`assettag` AS `a_assetTag`,
`a`.`issuedate` AS `a_issueDate`,`a`.`returndate` AS `a_returnDate`,
`a`.`school` AS `a_school`,`a`.`issuer` AS `a_issuer`,
`a`.`repossessor` AS `a_repossessor`,`a`.`loaner` AS `a_loaner`,
`a`.`backpack` AS `a_backpack`,`a`.`duckhead` AS `a_duckhead`,
`a`.`charger` AS `a_charger`,`a`.`laptop` AS `a_laptop`,
`a`.`user` AS `a_user`,
`s`.`uname` AS `s_uName`,`s`.`fname` AS `s_fName`,
`s`.`lname` AS `s_lName`,`s`.`test` AS `s_test`,
`s`.`studentid` AS `s_studentID`,`s`.`gradyear` AS `s_gradYear`,
`s`.`active` AS `s_active`,`s`.`grade` AS `s_grade`,
`s`.`tblgrade` AS `s_tblGrade`,`s`.`password` AS `s_password`,
`s`.`school` AS `s_school`,`s`.`mail` AS `s_mail`,
`s`.`lunch` AS `s_lunch`,
`s`.`dayuser` AS `s_dayuser`,
`la_laptop`.`timestamp` AS `LaptopReturnDate`,
( ( ( ( `la_laptop`.`timestamp` - `a`.`issuedate` ) / 60 ) /
60 ) / 24 ) AS `LaptopAssignmentLength`,
`la_backpack`.`timestamp` AS `BackpackReturnDate`,
`la_charger`.`timestamp` AS `ChargerReturnDate`,
`la_duckhead`.`timestamp` AS `DuckheadReturnDate`
FROM (((((((((((`computer` `c`
LEFT JOIN `assignment` `a`
ON(( `a`.`assettag` = `c`.`assettag` )))
LEFT JOIN `assignment` `a2`
ON(( ( `c`.`assettag` = `a2`.`assettag` )
AND ( ( `a`.`issuedate` < `a2`.`issuedate` )
OR ( ( `a`.`issuedate` =
`a2`.`issuedate` )
AND ( `a`.`assignmentid` <
`a2`.`assignmentid` ) ) ) )))
LEFT JOIN `log_assignment` `la_laptop`
ON(( ( `la_laptop`.`assignmentid` =
`a`.`assignmentid` )
AND ( `la_laptop`.`laptop` = 1 ) )))
LEFT JOIN `log_assignment` `la_laptop2`
ON(( ( `a`.`assignmentid` =
`la_laptop2`.`assignmentid` )
AND ( ( `la_laptop`.`timestamp` <
`la_laptop2`.`timestamp` )
OR ( ( `la_laptop`.`timestamp` =
`la_laptop2`.`timestamp` )
AND ( `la_laptop`.`logid` <
`la_laptop`.`logid` ) ) ) )))
LEFT JOIN `log_assignment` `la_backpack`
ON(( ( `la_backpack`.`assignmentid` =
`a`.`assignmentid` )
AND ( `la_backpack`.`backpack` = 1 ) )))
LEFT JOIN `log_assignment` `la_backpack2`
ON(( ( `a`.`assignmentid` =
`la_backpack2`.`assignmentid` )
AND ( ( `la_backpack`.`timestamp` <
`la_backpack2`.`timestamp` )
OR ( ( `la_backpack`.`timestamp` =
`la_backpack2`.`timestamp` )
AND ( `la_backpack`.`logid` <
`la_backpack`.`logid` ) ) ) )))
LEFT JOIN `log_assignment` `la_charger`
ON(( ( `la_charger`.`assignmentid` =
`a`.`assignmentid` )
AND ( `la_charger`.`charger` = 1 ) )))
LEFT JOIN `log_assignment` `la_charger2`
ON(( ( `a`.`assignmentid` =
`la_charger2`.`assignmentid` )
AND ( ( `la_charger`.`timestamp` <
`la_charger2`.`timestamp` )
OR ( ( `la_charger`.`timestamp` =
`la_charger2`.`timestamp` )
AND ( `la_charger`.`logid` <
`la_charger`.`logid` ) ) ) )))
LEFT JOIN `log_assignment` `la_duckhead`
ON(( ( `la_duckhead`.`assignmentid` = `a`.`assignmentid` )
AND ( `la_duckhead`.`duckhead` = 1 ) )))
LEFT JOIN `log_assignment` `la_duckhead2`
ON(( ( `a`.`assignmentid` = `la_duckhead2`.`assignmentid` )
AND ( ( `la_duckhead`.`timestamp` <
`la_duckhead2`.`timestamp` )
OR ( ( `la_duckhead`.`timestamp` =
`la_duckhead2`.`timestamp` )
AND ( `la_duckhead`.`logid` <
`la_duckhead`.`logid` ) ) ) )))
LEFT JOIN `student` `s`
ON(( `s`.`studentid` = `a`.`studentid` )))
WHERE ( ( 1 = 1 )
AND isnull(`a2`.`assignmentid`)
AND isnull(`la_laptop2`.`logid`)
AND isnull(`la_backpack2`.`logid`)
AND isnull(`la_charger2`.`logid`)
AND isnull(`la_duckhead2`.`logid`) )

Related

MySQL where condition based on select query

I am having the following query to fetch the data from the table.
SELECT rental_plans.*,
( ( inventory.total_inventory
+ vehicles.tmp_qty ) - Ifnull(reservation.total_reserved, 0) ) AS
vehicle_inventory
FROM `rental_plans`
INNER JOIN `vehicles`
ON `vehicles`.`id` = `rental_plans`.`vehicle_id`
LEFT JOIN (SELECT Count(*) AS total_inventory,
vehicle_id
FROM vehicle_inventories
GROUP BY vehicle_id) AS inventory
ON `inventory`.`vehicle_id` = `vehicles`.`id`
LEFT JOIN (SELECT vehicle_id,
Sum(qty) AS total_reserved
FROM `reservations`
WHERE ( '2018-12-18' BETWEEN pickup_date AND drop_date )
OR ( '2018-12-28' BETWEEN pickup_date AND drop_date )
AND `status` NOT IN ( 'RETURNED' )
GROUP BY `vehicle_id`) AS `reservation`
ON `rental_plans`.`vehicle_id` = `reservation`.`vehicle_id`
WHERE `rental_plans`.`id` > 0
AND `rental_plans`.`pickup` = '1'
AND `rental_plans`.`drop` = '10'
ORDER BY `rental_plans`.`price` ASC
But I want to handle where condition based on vehicle_inventory.
I tried with ... AND vehicle_inventory > 16 order by `rental_plans`.`price` ASC but this generates the error that column not found in the table
The reason is that vehicle_inventory is an alias and it is resolved after WHERE clause. You can read about that here. You can do something like:
SELECT *
FROM (SELECT rental_plans.*,
( ( inventory.total_inventory
+ vehicles.tmp_qty ) - Ifnull(reservation.total_reserved, 0)
) AS
vehicle_inventory
FROM `rental_plans`
INNER JOIN `vehicles`
ON `vehicles`.`id` = `rental_plans`.`vehicle_id`
LEFT JOIN (SELECT Count(*) AS total_inventory,
vehicle_id
FROM vehicle_inventories
GROUP BY vehicle_id) AS inventory
ON `inventory`.`vehicle_id` = `vehicles`.`id`
LEFT JOIN (SELECT vehicle_id,
Sum(qty) AS total_reserved
FROM `reservations`
WHERE ( '2018-12-18' BETWEEN
pickup_date AND drop_date )
OR ( '2018-12-28' BETWEEN
pickup_date AND drop_date )
AND `status` NOT IN ( 'RETURNED' )
GROUP BY `vehicle_id`) AS `reservation`
ON `rental_plans`.`vehicle_id` =
`reservation`.`vehicle_id`
WHERE `rental_plans`.`id` > 0
AND `rental_plans`.`pickup` = '1'
AND `rental_plans`.`drop` = '10')a
WHERE a.rental_plans > 16
ORDER BY `price` ASC
or
SELECT rental_plans.*,
( (inventory.total_inventory + vehicles.tmp_qty) - Ifnull(reservation.total_reserved, 0) ) AS vehicle_inventory
FROM `rental_plans`
INNER JOIN `vehicles`
ON `vehicles`.`id` = `rental_plans`.`vehicle_id`
LEFT JOIN
(
SELECT Count(*) AS total_inventory,
vehicle_id
FROM vehicle_inventories
GROUP BY vehicle_id) AS inventory
ON `inventory`.`vehicle_id` = `vehicles`.`id`
LEFT JOIN
(
SELECT vehicle_id,
Sum(qty) AS total_reserved
FROM `reservations`
WHERE (
'2018-12-18' BETWEEN pickup_date AND drop_date)
OR (
'2018-12-28' BETWEEN pickup_date AND drop_date)
AND `status` NOT IN ('RETURNED')
GROUP BY `vehicle_id`) AS `reservation`
ON `rental_plans`.`vehicle_id` = `reservation`.`vehicle_id`
WHERE `rental_plans`.`id` > 0
AND `rental_plans`.`pickup` = '1'
AND `rental_plans`.`drop` = '10'
where (
inventory.total_inventory + vehicles.tmp_qty) - ifnull(reservation.total_reserved, 0) > 16
ORDER BY `rental_plans`.`price` ASC

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

Query extremely slow

I am running the below query, but its extremeely slow. Dows anyone have any advice on how I can optimize it to improve performance.
The main user table only has 2700 row.
The query is:
SELECT
(
SELECT
core_org_chart.translation
FROM
core_org_chart
WHERE
(
core_org_chart.id_dir = t1.idOrg
)
) AS region,
(
SELECT
core_org_chart.translation
FROM
core_org_chart
WHERE
(
core_org_chart.id_dir = t2.idOrg
)
) AS level1,
(
SELECT
core_org_chart.translation
FROM
core_org_chart
WHERE
(
core_org_chart.id_dir = t3.idOrg
)
) AS level2,
(
SELECT
core_org_chart.translation
FROM
core_org_chart
WHERE
(
core_org_chart.id_dir = t4.idOrg
)
) AS level3,
core_user.firstname AS firstname,
core_user.lastname AS lastname,
core_user.email AS email,
core_user.register_date AS register_date,
core_user.lastenter AS lastenter,
(
SELECT
core_field_son.translation
FROM
(
core_field_son
JOIN core_field_userentry ON (
(
core_field_userentry.user_entry = core_field_son.idSon
)
)
)
WHERE
(
(
core_field_userentry.id_user = core_user.idst
)
AND (
core_field_userentry.id_common = 4
)
)
) AS Gender,
(
SELECT
core_field_son.translation
FROM
(
core_field_son
JOIN core_field_userentry ON (
(
core_field_userentry.user_entry = core_field_son.idSon
)
)
)
WHERE
(
(
core_field_userentry.id_user = core_user.idst
)
AND (
core_field_userentry.id_common = 6
)
)
) AS Race,
IF (
(core_user.valid = 1),
'Active',
'Suspended'
) AS UserStatus,
(
SELECT
jet_designations.designation
FROM
jet_designations
WHERE
(
jet_designations.id = core_user.designation
)
) AS UserDesignation,
(
SELECT
jet_designations.designation
FROM
jet_designations
WHERE
(
jet_designations.id = core_user.reports_to
)
) AS Manager
FROM
(
(
(
(
(
core_org_chart_tree t1
LEFT JOIN core_org_chart_tree t2 ON (
(
t2.idParent = t1.idOrg
)
)
)
LEFT JOIN core_org_chart_tree t3 ON (
(
t3.idParent = t2.idOrg
)
)
)
LEFT JOIN core_org_chart_tree t4 ON (
(
t4.idParent = t3.idOrg
)
)
)
JOIN core_group_members ON (
(
core_group_members.idst =
IF (
isnull(t2.idOrg),
t1.idst_ocd,
IF (
isnull(t3.idOrg),
t2.idst_ocd,
IF (
isnull(t4.idOrg),
t3.idst_ocd,
t4.idst_ocd
)
)
)
)
)
)
JOIN core_user ON (
(
core_user.idst = core_group_members.idstMember
)
)
)
WHERE
(t1.lev = 1)
you are using multiple queries in one, joining them will improve performance.

How to use "ALIAS" in "WHERE" in MYSQL

I'm not getting to use "ALIAS" in the "WHERE" MYSQL, in code below I need to do something like:
AND ( custo_percapita_regiao + comissao_representante ) < consig.valor_pago_comissao_representante
========================== code ===========================
SELECT
`consig`.`id`,
`consig`.`referencia_prod`,
`consig`.`valor_liquido`,
`consig`.`percentual_comissao_representante`,
`consig`.`valor_pago_comissao_representante`,
`consult`.`id` AS id_consultor,
`consult`.`nome` nome_consultor,
`repres`.`id` AS id_representante,
`repres`.`nome` nome_representante,
(
( SELECT ( `custo_alimentacao` + `custo_gasolina` + `custo_hospedagem` + `outros_custos` )
FROM `regioes`
WHERE `id` = `consult`.`regiao`
) /
( SELECT COUNT(*)
FROM `consignacoes`
INNER JOIN `consultores` ON `consultores`.`id` = `consignacoes`.`consultor`
WHERE `consultores`.`regiao` = `consult`.`regiao`
AND `consignacoes`.`excluido` = "N"
AND `consignacoes`.`valor_primeiro_pagamento` > 0
)
) AS custo_percapita_regiao,
(`consig`.`valor_liquido` * `consig`.`percentual_comissao_representante` / 100 ) AS comissao_representante
FROM `consignacoes` `consig`
INNER JOIN `consultores` `consult` ON `consult`.`id` = `consig`.`consultor`
INNER JOIN `administradores` `repres` ON `repres`.`id` = `consig`.`representante`
WHERE `representante` = 3
AND `consig`.`excluido` = "N"
AND `consig`.`valor_primeiro_pagamento` > 0
ORDER BY `consult`.`regiao` ASC, `consult`.`nome`
Possibly like this:-
SELECT
`consig`.`id`,
`consig`.`referencia_prod`,
`consig`.`valor_liquido`,
`consig`.`percentual_comissao_representante`,
`consig`.`valor_pago_comissao_representante`,
`consult`.`id` AS id_consultor,
`consult`.`nome` nome_consultor,
`repres`.`id` AS id_representante,
`repres`.`nome` nome_representante,
Sub1.RegionTot / Sub2.RegionCount AS custo_percapita_regiao,
(`consig`.`valor_liquido` * `consig`.`percentual_comissao_representante` / 100 ) AS comissao_representante
FROM `consignacoes` `consig`
INNER JOIN `consultores` `consult` ON `consult`.`id` = `consig`.`consultor`
INNER JOIN `administradores` `repres` ON `repres`.`id` = `consig`.`representante`
LEFT OUTER JOIN
(
SELECT `id`, ( `custo_alimentacao` + `custo_gasolina` + `custo_hospedagem` + `outros_custos` ) AS RegionTot
FROM `regioes`
) Sub1 ON Sub1.id = `consult`.`regiao`
LEFT OUTER JOIN
(
SELECT `consultores`.`regiao`, COUNT(*) AS RegionCount
FROM `consignacoes`
INNER JOIN `consultores` ON `consultores`.`id` = `consignacoes`.`consultor`
WHERE `consignacoes`.`excluido` = "N"
AND `consignacoes`.`valor_primeiro_pagamento` > 0
GROUP BY `consultores`.`regiao`
) Sub2 ON Sub2.`regiao` = `consult`.`regiao`
WHERE `representante` = 3
AND `consig`.`excluido` = "N"
AND `consig`.`valor_primeiro_pagamento` > 0
AND (Sub1.RegionTot / Sub2.RegionCount) < (`consig`.`valor_liquido` * `consig`.`percentual_comissao_representante` / 100 )
ORDER BY `consult`.`regiao` ASC, `consult`.`nome`
(partly swapping the sub selects from correlated ones in the SELECT to joins so the values can easily be used)
Try using variables:
SET #custo_percapita_regiao = 0;
SET #comissao_representante = 0;
SELECT
`consig`.`id`,
`consig`.`referencia_prod`,
`consig`.`valor_liquido`,
`consig`.`percentual_comissao_representante`,
`consig`.`valor_pago_comissao_representante`,
`consult`.`id` AS id_consultor,
`consult`.`nome` nome_consultor,
`repres`.`id` AS id_representante,
`repres`.`nome` nome_representante,
#custo_percapita_regiao :=
(
( SELECT ( `custo_alimentacao` + `custo_gasolina` + `custo_hospedagem` + `outros_custos` )
FROM `regioes`
WHERE `id` = `consult`.`regiao`
) /
( SELECT COUNT(*)
FROM `consignacoes`
INNER JOIN `consultores` ON `consultores`.`id` = `consignacoes`.`consultor`
WHERE `consultores`.`regiao` = `consult`.`regiao`
AND `consignacoes`.`excluido` = "N"
AND `consignacoes`.`valor_primeiro_pagamento` > 0
)
) AS custo_percapita_regiao,
#comissao_representante := (`consig`.`valor_liquido` * `consig`.`percentual_comissao_representante` / 100 ) AS comissao_representante
FROM `consignacoes` `consig`
INNER JOIN `consultores` `consult` ON `consult`.`id` = `consig`.`consultor`
INNER JOIN `administradores` `repres` ON `repres`.`id` = `consig`.`representante`
WHERE `representante` = 3 AND (#custo_percapita_regiao + #comissao_representante ) < consig.valor_pago_comissao_representante
AND `consig`.`excluido` = "N"
AND `consig`.`valor_primeiro_pagamento` > 0
ORDER BY `consult`.`regiao` ASC, `consult`.`nome`

optimizing a union join inside select statement of other joins

I have a query I built in 3 -4 parts. This takes over 140secs to run once I add the union join with join. How can I change the union join to execute it faster.
SELECT
testing.CLIENTID,
testing.COMPANY,
testing.CONTACT,
testing.CONTACTID,
`orders`.`ORDERNO` AS `ORDERNO`,
`orders`.`BIDNO` AS `BIDNO`,
`projects`.`PROJID` AS `PROJID`,
`projects`.`PROJCODE` AS `PROJCODE`,
`projects`.`StartDate` AS `StartDate`,
`category`.`type` AS `CATEGORY`,
`projects`.`country` AS `COUNTRY`,
`projects`.`VALUE` AS `VALUE`,
`projects`.`PROCESSOR` AS `PROCESSOR`,
`projects`.`NES` AS `NES`,
`projects`.`SPECSALE` AS `SPECSALE`,
`projects`.`OFFICE` AS `OFFICE`,
`projects`.`LORM` AS `LORM`,
`lookupcountry`.`REGION` AS `REGION`
FROM
(
(
(
(
(
(
SELECT
contactmerge.CLIENTID,
contactmerge.CONTACT,
contactmerge.CONTACTID,
accountmerge.COMPANY
FROM
(
SELECT
`hdb`.`contacts`.`CONTACTID` AS `CONTACTID`,
`hdb`.`contacts`.`CLIENTID` AS `CLIENTID`,
concat(
`hdb`.`contacts`.`FIRSTNAME`,
" ",
`hdb`.`contacts`.`LASTNAME`
) AS CONTACT,
_utf8 'paradox' AS `SOURCEDATABASE`
FROM
`hdb`.`contacts`
UNION
SELECT
`sugarcrm`.`contacts`.`id` AS `CONTACTID`,
`sugarcrm`.`accounts_contacts`.`account_id` AS `CLIENTID`,
concat(
`sugarcrm`.`contacts`.`first_name`,
" ",
`sugarcrm`.`contacts`.`last_name`
) AS CONTACT,
_utf8 'sugar' AS `SOURCEDATABASE`
FROM
(
(
(
(
`sugarcrm`.`contacts`
LEFT JOIN `sugarcrm`.`email_addr_bean_rel` ON (
(
(
`sugarcrm`.`contacts`.`id` = `sugarcrm`.`email_addr_bean_rel`.`bean_id`
)
AND (
(
`sugarcrm`.`email_addr_bean_rel`.`primary_address` = 1
)
OR (
(
`sugarcrm`.`email_addr_bean_rel`.`primary_address` IS NOT NULL
)
AND (
`sugarcrm`.`email_addr_bean_rel`.`primary_address` <> 0
)
)
)
)
)
)
LEFT JOIN `sugarcrm`.`accounts_contacts` ON (
(
`sugarcrm`.`contacts`.`id` = `sugarcrm`.`accounts_contacts`.`contact_id`
)
)
)
JOIN `sugarcrm`.`email_addresses` ON (
(
`sugarcrm`.`email_addr_bean_rel`.`email_address_id` = `sugarcrm`.`email_addresses`.`id`
)
)
)
LEFT JOIN `sugarcrm`.`accounts` ON (
(
`sugarcrm`.`accounts`.`id` = `sugarcrm`.`accounts_contacts`.`account_id`
)
)
)
) AS contactmerge
LEFT JOIN (
SELECT
CLIENTID,
`hdb`.`clients`.`COMPANY` AS `COMPANY`
FROM
`hdb`.`clients`
UNION
SELECT
id AS CLIENTID,
`sugarcrm`.`accounts`.`name` AS `COMPANY`
FROM
`sugarcrm`.`accounts`
) AS accountmerge ON contactmerge.CLIENTID = accountmerge.CLIENTID
) AS testing
)
JOIN `orders` ON (
(
`testing`.`CONTACTID` = `orders`.`CONTACTID`
)
)
)
JOIN `projects` ON (
(
`orders`.`ORDERNO` = `projects`.`ORDERNO`
)
)
)
JOIN `category` ON (
(
`category`.`category_id` = `projects`.`category_id`
)
)
)
LEFT JOIN `lookupcountry` ON (
(
CONVERT (
`lookupcountry`.`COUNTRY` USING utf8
) = CONVERT (
`projects`.`country` USING utf8
)
)
)
)
ORDER BY
`testing`.`COMPANY`,
`projects`.`StartDate`
The table alias called testing is the one taking long to execute. I need to then turn this into a view
Original query without the joining of sugarcrm.
SELECT
`clients`.`CORPORATE` AS `CORPORATE`,
`clients`.`COMPANY` AS `COMPANY`,
`clients`.`CLIENTID` AS `CLIENTID`,
`contacts`.`CONTACTID` AS `CONTACTID`,
concat(
`contacts`.`LASTNAME`,
`contacts`.`FIRSTNAME`,
`contacts`.`INITIALS`
) AS `Contact`,
`orders`.`ORDERNO` AS `ORDERNO`,
`orders`.`BIDNO` AS `BIDNO`,
`projects`.`PROJID` AS `PROJID`,
`projects`.`PROJCODE` AS `PROJCODE`,
`projects`.`StartDate` AS `StartDate`,
`category`.`type` AS `CATEGORY`,
`projects`.`country` AS `COUNTRY`,
`projects`.`VALUE` AS `VALUE`,
`projects`.`PROCESSOR` AS `PROCESSOR`,
`projects`.`NES` AS `NES`,
`projects`.`SPECSALE` AS `SPECSALE`,
`projects`.`OFFICE` AS `OFFICE`,
`projects`.`LORM` AS `LORM`,
`lookupcountry`.`REGION` AS `REGION`
FROM
(
(
(
(
(
`clients`
JOIN `contacts` ON (
(
`clients`.`CLIENTID` = `contacts`.`CLIENTID`
)
)
)
JOIN `orders` ON (
(
`contacts`.`CONTACTID` = `orders`.`CONTACTID`
)
)
)
JOIN `projects` ON (
(
`orders`.`ORDERNO` = `projects`.`ORDERNO`
)
)
)
JOIN `category` ON (
(
`category`.`category_id` = `projects`.`category_id`
)
)
)
LEFT JOIN `lookupcountry` ON (
(
CONVERT (
`lookupcountry`.`COUNTRY` USING utf8
) = CONVERT (
`projects`.`country` USING utf8
)
)
)
)
ORDER BY
`clients`.`CORPORATE`,
`clients`.`COMPANY`,
`contacts`.`LASTNAME`,
`projects`.`StartDate`
Your LEFT JOIN from sugarcrm.contacts to sugarcrm.email_addr_bean_rel
ON the id=bean_id is ok, but then your test for Primary_Address = 1
OR ( primary address IS NOT NULL AND primary_address <> 0 ) is wasteful.
Not null mean it has a value. The first qualifier of 1 is ok, but then
you test for any address not equal to 0 (thus 1 is, but so is 2, 3, 400, 1809 or
any other number. So why not just take how I've simplified it.
SELECT
O.ORDERNO,
O.BIDNO,
CASE when c.ContactID IS NULL
then sc.id
ELSE c.contactid END as ContactID,
CASE when c.ContactID IS NULL
then sac.account_id
ELSE c.clientid END as ClientID,
CASE when c.ContactID IS NULL
then concat( sc.first_name, " ", sc.last_name )
ELSE concat( c.FIRSTNAME, " ", c.LASTNAME ) END as Contact,
CASE when c.ContactID IS NULL
then sCli.`name`
ELSE cCli.Company END as Company,
CASE when c.ContactID IS NULL
then _utf8 'sugar'
ELSE _utf8 'paradox' END as SOURCEDATABASE,
P.PROJID,
P.PROJCODE,
P.StartDate,
Cat.`type` AS CATEGORY,
P.`country` AS COUNTRY,
P.`VALUE` AS `VALUE`,
P.PROCESSOR,
P.NES,
P.SPECSALE,
P.OFFICE,
P.LORM,
LC.REGION
FROM
orders O
JOIN projects P
ON O.ORDERNO = P.ORDERNO
JOIN category Cat
ON P.category_id = Cat.category_id
LEFT JOIN lookupcountry LC
ON CONVERT( P.`country` USING utf8 ) = CONVERT( LC.COUNTRY USING utf8 )
LEFT JOIN hdb.contacts c
ON O.ContactID = c.ClientID
LEFT JOIN hdb.clients cCli
ON c.ClientID = cCli.ClientID
LEFT JOIN sugarcrm.contacts sc
ON O.ContactID = sc.id
LEFT JOIN sugarcrm.accounts sCli
ON sc.id = sCli.id
LEFT JOIN sugarcrm.accounts_contacts sac
ON sc.id = sac.contact_id
LEFT JOIN sugarcrm.accounts Acc
ON sac.account_id = Acc.id
LEFT JOIN sugarcrm.email_addr_bean_rel EABR
ON sc.id = EABR.bean_id
AND EABR.primary_address IS NOT NULL
LEFT JOIN sugarcrm.email_addresses EA
ON EABR.email_address_id = EA.id
ORDER BY
CASE when c.ContactID IS NULL
then sCli.`name`
ELSE cCli.Company END,
P.StartDate
I don't mind helping, but from now on, you should take a look at what I'm doing... Establish the relationships... Start with the basis of your data (orders) and look at ONE PATH on how to connect to your "contacts" table... Write those joins (as left-joins). THEN, write your paths to the SUGAR account contacts and write THOSE joins (also left-joins). Don't try to prequery all possible contacts, but using the CASE/WHEN to determine which to get based on a null route vs not just as I have with the contact, client, company, etc. You will get the data from one path vs the other... just keep it consistent.