Parentheses in mysql query giving different results - mysql

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);

Related

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.

MYSQL UNION JOIN SUM(amount) output two result instead of one

I have this below:
SELECT a.* FROM ( SELECT
asset_liability_income_expenditure_tbl.a_l_code,
SUM(mainaccount_a_2017.amount), mainaccount_a_2017.dr_cr_action
FROM `mainaccount_a_2017` LEFT JOIN chart_of_account
ON (
chart_of_account.joint_account_numbers =
mainaccount_a_2017.joint_account_number
)
LEFT JOIN asset_liability_income_expenditure_tbl
ON (
asset_liability_income_expenditure_tbl.a_l_code =
chart_of_account.account_type
)
WHERE asset_liability_income_expenditure_tbl.a_l_code = 'FA'
AND mainaccount_a_2017.dr_cr_action = 'DR' UNION
SELECT asset_liability_income_expenditure_tbl.a_l_code,
SUM(mainaccount_b_2017.amount),
mainaccount_b_2017.dr_cr_action
FROM `mainaccount_b_2017`
LEFT JOIN chart_of_account ON (
chart_of_account.joint_account_numbers =
mainaccount_b_2017.joint_account_number
)
LEFT JOIN asset_liability_income_expenditure_tbl ON (
asset_liability_income_expenditure_tbl.a_l_code =
chart_of_account.account_type
)
WHERE asset_liability_income_expenditure_tbl.a_l_code = 'FA'
AND mainaccount_b_2017.dr_cr_action = 'DR'
) AS a
it works fine, but displays either one empty row at the top and the sum below or vis-a-vis. I tried LIMIT 1, but the problem is when the SUM(amount) outputs in row 2, i cannot fetch and if I don't apply any limit, it only fetches result whose SUM(amount) outputs in row 1. I don't know what am missing. Please kindly assist. Thanks.
I figured it out. I had to flip something. Results below:
SELECT SUM(a) FROM
(
SELECT SUM(mainaccount_a_2017.amount)
AS a FROM `mainaccount_a_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_a_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE asset_liability_income_expenditure_tbl.a_l_code = 'FA'
AND mainaccount_a_2017.dr_cr_action = 'DR'
UNION ALL
SELECT SUM(mainaccount_b_2017.amount)
AS a FROM `mainaccount_b_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_b_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE asset_liability_income_expenditure_tbl.a_l_code = 'FA' AND mainaccount_b_2017.dr_cr_action = 'DR'
) a

Why MYSQL doesn't use my indexes?

I have table karton00 which holds thousands of records. This makes the queries slow. I would like to use indexes, but even though I set them, they are not being used.
Here is my table. and here is the result of using EXPLAIN.
This is my query:
SELECT '' checkbox,
k00_eszkozid,
k00_eszkoznev,
k01_gyariszam,
k01_leltszam,
prsn_name,
k00_status,
tstikon,
k00_startflow,
tstname,
k00_eszkozid,
k01_gyariszam,
k01_leltszam
FROM karton00
LEFT JOIN karton01
ON k00_eszkozid = k01_eszkozid
AND k01_status = 'A'
LEFT JOIN karton02
ON k00_eszkozid = k02_eszkozid
AND k02_status = 'A'
LEFT JOIN karton04
ON k00_eszkozid = k04_eszkozid
AND k04_status = 'A'
LEFT JOIN karton05
ON k00_eszkozid = k05_eszkozid
AND k05_status = 'A'
LEFT JOIN karton06
ON k00_eszkozid = k06_eszkozid
AND k06_status = 'A'
LEFT JOIN karton08
ON k00_eszkozid = k08_eszkozid
AND k08_status = 'A'
LEFT JOIN karton09
ON k00_eszkozid = k09_eszkozid
AND k09_status = 'A'
LEFT JOIN telephely et
ON k06_telephelyid = et.telepid
LEFT JOIN ktghely00 ek
ON k02_ktghid = ek.ktghid
LEFT JOIN person00 us
ON k06_userid = prsn_id
LEFT JOIN ktghely00 fk
ON prsn_ktgh = fk.ktghid
LEFT JOIN telephely ft
ON prsn_telep = ft.telepid
LEFT JOIN tamstatus
ON k02_tamstatusid = tstid
LEFT JOIN szakleltar
ON k02_szakleltarid = szleltid
LEFT JOIN tamszerv
ON k02_tamszervid = tszid
LEFT JOIN ktghely01
ON k02_vgazdaid = vgid
AND vgstatus = 'A'
LEFT JOIN ktghely00 vk
ON vgktghid = vk.ktghid
LEFT JOIN szallitok m
ON k05_mincegid = m.szallid
LEFT JOIN szallitok s
ON k04_szallitoid = s.szallid
LEFT JOIN dctnry00 ym
ON k05_minosit = ym.dctnryname
AND ym.dctnrygrp = 'YESNO'
LEFT JOIN dctnry00 yd
ON k05_check = yd.dctnryname
AND yd.dctnrygrp = 'YESNO'
WHERE k00_status IN ( 'A', 'H' )
AND ( k02_vgazdaid IN ( 7 ) )
AND NOT EXISTS (SELECT *
FROM eszkozkizar
WHERE ez_flid = 0
AND ez_emintaid = k00_eszkozmintaid
AND k00_uzembedatum < ( Date_add(Curdate(),
INTERVAL ez_honap month) )
AND k00_uzembedatum != ''
AND k02_vgazdaid NOT IN ( 7 ))
AND NOT EXISTS(SELECT *
FROM eszkozkizar
WHERE ez_flid = 0
AND ez_emintaid = k00_eszkozmintaid
AND k02_tamszervid = ez_tamszerv
AND k02_tamstatusid = ez_tamsts
AND k00_uzembedatum < ( Date_add(Curdate(),
INTERVAL ez_honap month) )
AND k00_uzembedatum != ''
AND k02_vgazdaid NOT IN ( 7 ))
ORDER BY k00_eszkoznev ASC;
Also you can use USE INDEX (index_list) statement: http://dev.mysql.com/doc/refman/5.5/en/index-hints.html

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