How to use "ALIAS" in "WHERE" in MYSQL - 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`

Related

Parentheses in mysql query giving different results

I have a query that is giving me different results when i enclosed it in Parentheses, however when I run it without Parentheses its giving me different results. I want to apply Union in between so I have to use Parentheses as without union doesn't work.
The query is as follows:
SELECT Distinct
recurring_billing.id,
recurring_billing.kid_id,
recurring_billing.class_id,
recurring_billing.app_id,
recurring_billing.Region_ID,
CC.month_name,
CC.billing_year,
CASE
WHEN
CC.month_name = recurring_billing.billing_month
AND CC.billing_year = recurring_billing.billing_year
THEN
recurring_billing.billing_status
ELSE
'Pending'
END
AS billing_status, tblkids.kid_name, tblkids.kid_Lastname, tblkids.kid_EMail, tbl_app.app_CCExp AS cc_exp, tbl_app.app_CCName AS cc_name, tbl_app.app_CCNumber AS cc_number, tbl_app.app_CCType AS cc_type, tblclasses.cla_EndDate, tblclassdays.classday_day, CC.remainingclasses, tbl_app.cost_per_class, CC.remainingclasses * tbl_app.cost_per_class AS cost_amount,
CASE
WHEN
OP.override_amt IS NOT NULL
THEN
OP.override_amt
ELSE
CC.remainingclasses * tbl_app.cost_per_class
END
AS pmt_amount,
CASE
WHEN
OP.process_payment = False
THEN
OP.process_payment
ELSE
True
END
AS process_payment
FROM
recurring_billing
LEFT JOIN
tblkidsxclass
ON recurring_billing.kid_id = tblkidsxclass.kxc_kidid
AND recurring_billing.app_id = tblkidsxclass.kxc_appid
LEFT JOIN
tbl_app
ON recurring_billing.app_ID = tbl_app.app_ID
LEFT JOIN
tblkids
ON recurring_billing.kid_id = tblkids.kid_ID
LEFT JOIN
tblclasses
ON recurring_billing.class_id = tblclasses.cla_ID
LEFT JOIN
tblclassdays
ON tblclasses.cla_ID = tblclassdays.classday_classID
INNER JOIN
(
SELECT
MONTHNAME(classday_day) AS month_name,
YEAR(classday_day) AS billing_year,
cla_ID,
COUNT(classday_classid) AS remainingclasses,
c.cost_per_class AS cost_per_class,
COUNT(classday_classid) * cost_per_class AS TotalClassCost
FROM
tblclassdays
JOIN
(
SELECT
tblclasses.cla_ID,
tblclasses.cost_per_class,
tblclasses.cla_nextclass AS next1,
tblclasses_1.cla_nextclass AS next2
FROM
tblclasses
LEFT JOIN
tblclasses AS tblclasses_1
ON tblclasses.cla_nextclass = tblclasses_1.cla_ID
WHERE
tblclasses.cla_ID IN
(
SELECT DISTINCT
recurring_billing.class_id
FROM
recurring_billing
LEFT JOIN
tblkidsxclass
ON recurring_billing.kid_id = tblkidsxclass.kxc_kidid
AND recurring_billing.app_id = tblkidsxclass.kxc_appid -- LEFT JOIN tblkids ON recurring_billing.kid_id = tblkids.kid_ID
LEFT JOIN
tblclasses
ON recurring_billing.class_id = tblclasses.cla_ID -- LEFT JOIN tblclassdays ON tblclasses.cla_ID = tblclassdays.classday_classID
WHERE
ISNULL(tblkidsxclass.kxc_dropoutdate)
AND tblkidsxclass.pmt_option = 'Recurring'
AND tblclasses.cla_active = TRUE -- AND tblclasses.cla_EndDate >= NOW()
GROUP BY
recurring_billing.id
)
)
c
ON tblclassdays.classday_classid IN
(
c.cla_ID,
c.next1,
c.next2
)
WHERE
tblclassdays.classday_noclass = FALSE
AND MONTH(classday_day) = 11
AND YEAR(classday_day) = 2020
AND
(
CONCAT(CAST(classday_day AS DATE), ' ', CAST(classday_endtime AS TIME)) > CAST(CURDATE() AS DATETIME)
)
GROUP BY
cla_ID
)
CC
ON CC.cla_ID = tblclassdays.classday_classID
LEFT JOIN
override_payments OP
ON recurring_billing.app_id = OP.app_id
AND recurring_billing.kid_id = OP.kid_id
AND CC.month_name = OP.billing_month
AND CC.billing_year = OP.billing_year
WHERE
ISNULL(tblkidsxclass.kxc_dropoutdate)
AND tblkidsxclass.pmt_option = 'Recurring'
AND tblclasses.cla_active = TRUE
AND recurring_billing.kid_id NOT IN
(
SELECT
kid_id
from
recurring_billing
where
billing_month = 'November'
and billing_year = '2020'
)
-- AND tblclasses.cla_EndDate >= NOW()
GROUP BY
recurring_billing.id
ORDER BY
recurring_billing.id ASC
Same query if enclosed in Parentheses will give me different results.
Parentheses are not required for a UNION statement. The following 2 union statements both work and yield the same results.
SELECT 1 UNION SELECT 2;
(SELECT 1) UNION (SELECT 2);

UPDATE - SELECT - MYSQL #1093 - You can't specify target table 'temp1' for update in FROM clause

I can't find solution to correct this big query, I always receive an error from database.
I have tre tables and I need to make changes on some attribute on some condition:
UPDATE o36t_orders as temp1,
mytable as temp2
SET
temp1.bonifico = 1,
temp2.ultimo = 1
WHERE
temp1.id_order IN (
SELECT
id_order
FROM o36t_orders
LEFT JOIN o36t_address ON (o36t_address.id_address = o36t_orders.id_address_delivery)
LEFT JOIN mytable ON (
mytable.Causale = CONCAT(
o36t_address.lastname,
' ',
o36t_address.firstname
)
)
WHERE
o36t_orders.bonifico <> 1
)
AND temp2.id IN (
SELECT
id
FROM o36t_orders
LEFT JOIN o36t_address ON (o36t_address.id_address = o36t_orders.id_address_delivery)
LEFT JOIN mytable ON (
mytable.Causale = CONCAT(
o36t_address.lastname,
' ',
o36t_address.firstname
)
)
WHERE
o36t_orders.bonifico <> 1
)
Since the subqueries of the 2 IN clauses are identical (except the retuned column), I think that you can do what you want by a straight inner join of the 2 tables and that subquery (returning both columns):
UPDATE o36t_orders temp1
INNER JOIN (
SELECT
id, id_order
FROM o36t_orders
LEFT JOIN o36t_address ON (o36t_address.id_address = o36t_orders.id_address_delivery)
LEFT JOIN mytable ON (
mytable.Causale = CONCAT(
o36t_address.lastname,
' ',
o36t_address.firstname
)
)
WHERE
o36t_orders.bonifico <> 1
) t ON t.id_order = temp1.id_order
INNER JOIN mytable temp2 ON temp2.id = t.id
SET
temp1.bonifico = 1,
temp2.ultimo = 1

Optimising MYSQL query with row number

SELECT o.* FROM ( SELECT
#rownum := #rownum + 1 RN,
i.* FROM<br>
(
SELECT
#rownum:=0
)
r,<br>
(
SELECT DISTINCT<br>
CG_MGR_USR.MANAGER_NAME,<br>
CG_MGR_USR.PARAM_NAME,<br>
USR_TR_DATA.USER_ID,<br>
CG_MGRS.FIRST_NAME,<br>
CG_MGRS.LAST_NAME,<br>
CC_GENOBJ.OBJNAME,<br>
USR_TR_DATA.RISK_ID,<br>
USR_TR_DATA.VERSION_ID,<br>
T_RISK.RISK_DESCR,<br>
CC_RISKT.RISK_ID CC_RISK,<br>
CC_RISKT.DESCN,<br>
USR_TR_DATA.SYSTEM_ID,<br>
T_STATUS.STATUS,<br>
USR_TR_DATA.COUNTS,<br>
SYSTEMS.SYSTEM_NAME<br>
FROM
TABLE_USR_TR_DATA USR_TR_DATA<br>
LEFT OUTER JOIN TABLE_CC_GENOBJ CC_GENOBJ<br>
ON
CC_GENOBJ.GENOBJTP = 1
AND CC_GENOBJ.SYSTEM_ID IN<br>
(
SELECT
sys_id
FROM
TABLE_CS_SYSTEM
WHERE
cs_sys_id =USR_TR_DATA.system_id
AND is_primary='Y'
)<br>
AND CC_GENOBJ.GENOBJID = USR_TR_DATA.USER_ID,<br>
TABLE_RISK T_RISK<br>
LEFT OUTER JOIN TABLE_CC_RISKT CC_RISKT
ON<br>
CC_RISKT.LANG = 'EN'
AND T_RISK.CC_RISK_ID = CC_RISKT.RISK_ID,<br>
TABLE_CG_MGR_USR CG_MGR_USR,<br>
TABLE_CG_MGRS CG_MGRS,<br>
TABLE_STATUS T_STATUS,<br>
TABLE_CS_SYSTEM CS_SYSTEMS,<br>
TABLE_SYSTEMS SYSTEMS<br>
WHERE
USR_TR_DATA.RISK_ID = T_RISK.RISK_ID<br>
AND USR_TR_DATA.VERSION_ID = T_RISK.VERSION_ID<br>
AND CG_MGR_USR.USER_NAME = USR_TR_DATA.USER_ID<br>
AND CG_MGR_USR.SYSTEM_ID = CS_SYSTEMS.SYS_ID<br>
AND CG_MGRS.MANAGER_NAME = CG_MGR_USR.MANAGER_NAME<br>
AND CG_MGRS.PARAM_NAME =CG_MGR_USR.PARAM_NAME<br>
AND CG_MGRS.SYSTEM_ID = CG_MGR_USR.SYSTEM_ID<br>
AND CS_SYSTEMS.CS_SYS_ID = USR_TR_DATA.SYSTEM_ID<br>
AND CS_SYSTEMS.IS_PRIMARY = 'Y'<br>
AND T_STATUS.SEQ_NO = USR_TR_DATA.STATUS_ID<br>
AND SYSTEMS.SYSTEMS_ID = USR_TR_DATA.SYSTEM_ID<br>
AND CG_MGR_USR.MANAGER_NAME IN( 'SAPUSER' )<br>
AND T_STATUS.STATUS IN( 'IN-PROCESS', 'OPEN' )<br>
AND USR_TR_DATA.COUNTS >= 1<br>
ORDER BY
USER_ID,
SYSTEM_ID,
RISK_ID,
VERSION_ID,
CC_RISK,
STATUS,
COUNTS ASC
)
i ) o <br>WHERE o.RN >= 1 AND o.RN <= 10
It is taking too much time for to fetch only 10 records.

Error when Multiple JOINS are used

I'm trying to execute the following query, Bu it gives a syntax error, Can some point me were the problem is?
select count(*) from (((
select * from testlink1915.TL_tcversions where execution_type = 2 and id = 66134) c
JOIN (select * from testlink1915.TL_nodes_heirachy) d
ON id = testlink1915.TL_nodes_heirachy.parent_id) a
JOIN (select * FROM testlink1915.TL_req_coverage where req_id = 67635) b
ON a.id = b.testcase_id);
Error appeared only when I added the following segment.
c JOIN (select * from testlink1915.TL_nodes_heirachy) d
ON id = testlink1915.TL_nodes_heirachy.parent_id
The error
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'a JOIN (select * FROM testlink1915.TL_req_coverage where req_id = 67635) b ON a.' at line 1
Use:
c.id = d.parent_id
instead of
id = testlink1915.TL_nodes_heirachy.parent_id
Try this:
select count(*)
from (
select *
from (
select *
from (
select *
from testlink1915.TL_tcversions
where execution_type = 2
and id = 66134
) c join (
select *
from testlink1915.TL_nodes_heirachy
) d on c.id = d.parent_id
) a join (
select *
from testlink1915.TL_req_coverage
where req_id = 67635
) b on a.id = b.testcase_id
) t;
Please note that I use * everywhere. Replace it with the columns you need.
Please Try this
select count(1) from
(
select * from (
select * from testlink1915.TL_tcversions where execution_type = 2 and id = 66134 ) c
JOIN
(select * from testlink1915.TL_nodes_heirachy) d on a.id=d.parent_id
join
(select * FROM testlink1915.TL_req_coverage where req_id = 67635) a ON a.id = b.testcase_id
) as E join (select * from testlink1915.TL_nodes_heirachy) F ON E.id = F.parent_id
Try below query :
select count(*) from
(
(
select * from testlink1915.TL_tcversions
JOIN testlink1915.TL_nodes_heirachy ON id =
testlink1915.TL_nodes_heirachy.parent_id where execution_type = 2 and id
= 66134
) a
JOIN
(
select * FROM testlink1915.TL_req_coverage where req_id = 67635
) ON a.id = b.testcase_id
) ;

How to optimize for speed a sql multiple select with SUM

I have a really long select from my database with many joins. The problem is with counting SUM: without sum, select time is about 3s, but with SUM is about 15s.
Is it possible to optimize my select to obtain a shorter select time?
Here is my code:
SELECT
accomodation.id,
accomodation.aid,
accomodation.title_en,
accomodation.title_url_en,
accomodation.address,
accomodation.zip,
accomodation.stars,
accomodation.picture,
accomodation.valid_from,
accomodation.valid_to,
accomodation.latitude,
accomodation.longitude,
accomodation.city_id AS
accomodation_city_id,
db_cities.id AS city_id,
db_cities.title_en AS city,
db_cities.title_url AS city_url,
db_countries.title_en AS country_title,
db_countries.title_url_en AS country_url,
accomodation_type.class AS accomodation_type_class,
accomodation_review_value_total.value AS review_total,
MIN(accomodation_price.price) AS price_from,
accomodation_rooms.total_persons
FROM
(SELECT aid, MAX(info_date_add) AS max_info_date_add FROM accomodation GROUP BY aid) accomodation_max
INNER JOIN accomodation
ON
accomodation_max.aid = accomodation.aid AND
accomodation_max.max_info_date_add = accomodation.info_date_add
LEFT JOIN db_cities
ON (
db_cities.id = accomodation.city_id OR
(((acos(sin((db_cities.latitude*pi()/180)) * sin((accomodation.latitude*pi()/180)) + cos((db_cities.latitude*pi()/180)) * cos((accomodation.latitude*pi()/180)) * cos(((db_cities.longitude - accomodation.longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) < '20')
JOIN db_countries
ON db_countries.id = accomodation.country_id
LEFT JOIN accomodation_review_value_total
ON accomodation_review_value_total.accomodation_aid = accomodation.aid
LEFT JOIN accomodation_type_value
ON accomodation_type_value.accomodation_id = accomodation.id
LEFT JOIN accomodation_type
ON accomodation_type.id = accomodation_type_value.accomodation_type_id
JOIN accomodation_season
ON (
accomodation_season.accomodation_aid = accomodation.aid AND
( '2013-11-04' BETWEEN accomodation_season.start_date AND accomodation_season.end_date OR '2013-11-05' BETWEEN accomodation_season.start_date AND accomodation_season.end_date ) )
JOIN accomodation_price
ON
accomodation_price.accomodation_aid = accomodation.aid AND
accomodation_price.accomodation_price_type_id = '1' AND
accomodation_price.accomodation_price_cat_id = '1' AND
accomodation_price.price BETWEEN '20' AND '250' AND
accomodation_price.accomodation_season_id = accomodation_season.id
JOIN accomodation_theme_value
ON accomodation_theme_value.accomodation_id = accomodation.id
INNER JOIN
(SELECT
accomodation_id,
SUM(accomodation_rooms.rooms) AS total_rooms,
SUM(accomodation_rooms.beds * accomodation_rooms.rooms) AS total_persons
FROM accomodation_rooms
GROUP BY accomodation_id) accomodation_rooms
ON
accomodation_rooms.accomodation_id = accomodation.id AND
accomodation_rooms.total_persons >= '4'
WHERE
db_countries.title_url_en LIKE '%spain%' AND
db_cities.title_url LIKE '%barcelona%' AND
accomodation_type_value.accomodation_type_id IN (5,10) AND
total_rooms >= '2' AND
accomodation_theme_value.accomodation_theme_id IN (11,12,13) AND
accomodation.stars IN (3,4,5) AND
( accomodation_review_value_total.value >= '4.5' ) AND
db_cities.id = '2416'
GROUP BY accomodation.aid
ORDER BY
CASE
WHEN accomodation.valid_to>=NOW() AND accomodation.valid_from<=NOW() AND MIN(accomodation_price.price) IS NOT NULL THEN 0
WHEN NOW()>accomodation.valid_to AND accomodation.valid_to>'0000-00-00' AND MIN(accomodation_price.price) IS NOT NULL THEN 1
WHEN accomodation.valid_to>=NOW() AND accomodation.valid_from<=NOW() THEN 2
WHEN NOW()>accomodation.valid_to AND accomodation.valid_to>'0000-00-00' THEN 3
ELSE 4 END,
review_total DESC,
accomodation.title_en
LIMIT 10