Data Conversion while creating table in MYSQL - mysql

Error while creating table but the SQL is retrieving result
Please find the below code, the below SQL by itself is working fine retrieving results!
SELECT
CASE WHEN J.JOBID = DJ.JOBNUMBER
THEN DJ.JOBID ELSE J.JOBID
END AS JOBID,
J.DISTRICTID,
CASE WHEN D.DISTRICTID = J.DISTRICTID
THEN D.NAME ELSE NULL
END AS DISTRICT_NAME,
D.SEGMENTID,
CASE WHEN D.SEGMENTID = S.SEGMENTID AND D.DISTRICTID = J.DISTRICTID
THEN S.NAME ELSE NULL
END AS SEGMENT,
J.STARTTIME,
J.ENDTIME,
SJ.COMCATJOBTYPEID,
J.JOBTYPEID,
CASE WHEN J.JOBTYPEID = JT.JOBTYPEID
THEN JT.NAME ELSE NULL
END AS JOBTYPENAME,
TS.SSSEGMENT AS SUBPL_NAME,
CONCAT(D.DISTRICTID,TS.SSSEGMENT) AS DISTRICTSUBPLID
FROM `EAR-AA-242`.JOB J
LEFT JOIN `EAR-AA-242`.DISTRICT D ON J.DISTRICTID = D.DISTRICTID
LEFT JOIN `EAR-AA-242`.DMJOB DJ ON DJ.JOBNUMBER = J.JOBID
LEFT JOIN `EAR-AA-242`.JOBTYPE JT ON JT.JOBTYPEID = J.JOBTYPEID
LEFT JOIN `EAR-AA-242`.STANDARDJOBTYPE SJ ON JT.STANDARDJOBTYPEID = SJ.STANDARDJOBTYPEID
LEFT JOIN `EAR-AA-239`.TBLJOBTYPE TJ ON SJ.COMCATJOBTYPEID = TJ.JOBTYPEID
LEFT JOIN (SELECT SS.SSSEGMENT, SS.NODEID FROM `EAR-AA-239`.TBLSSSEGMENT S,
`EAR-AA-239`.TBLSSSEGMENT SS WHERE S.SSS = SS.PARENTSSS AND SS.DELETED = 0) TS ON TJ.SSSEGMENT =TS.NODEID
LEFT JOIN `EAR-AA-242`.SEGMENT S ON S.SEGMENTID = D.SEGMENTID
WHERE DATE(J.STARTTIME) > DATE_SUB(DATE(SYSDATE()), INTERVAL 367 DAY)
ORDER BY J.JOBID;
The same code code , while creating a table is throwing an
Error Code: 1292. Truncated incorrect DOUBLE value: '11COC0011'
CREATE TABLE ODS.JOB_LOCATION_IDISTRICT AS
SELECT
CASE WHEN J.JOBID = DJ.JOBNUMBER
THEN DJ.JOBID ELSE J.JOBID
END AS JOBID,
J.DISTRICTID,
CASE WHEN D.DISTRICTID = J.DISTRICTID
THEN D.NAME ELSE NULL
END AS DISTRICT_NAME,
D.SEGMENTID,
CASE WHEN D.SEGMENTID = S.SEGMENTID AND D.DISTRICTID = J.DISTRICTID
THEN S.NAME ELSE NULL
END AS SEGMENT,
J.STARTTIME,
J.ENDTIME,
SJ.COMCATJOBTYPEID,
J.JOBTYPEID,
CASE WHEN J.JOBTYPEID = JT.JOBTYPEID
THEN JT.NAME ELSE NULL
END AS JOBTYPENAME,
TS.SSSEGMENT AS SUBPL_NAME,
CONCAT(D.DISTRICTID,TS.SSSEGMENT) AS DISTRICTSUBPLID
FROM `EAR-AA-242`.JOB J
LEFT JOIN `EAR-AA-242`.DISTRICT D ON J.DISTRICTID = D.DISTRICTID
LEFT JOIN `EAR-AA-242`.DMJOB DJ ON DJ.JOBNUMBER = J.JOBID
LEFT JOIN `EAR-AA-242`.JOBTYPE JT ON JT.JOBTYPEID = J.JOBTYPEID
LEFT JOIN `EAR-AA-242`.STANDARDJOBTYPE SJ ON JT.STANDARDJOBTYPEID = SJ.STANDARDJOBTYPEID
LEFT JOIN `EAR-AA-239`.TBLJOBTYPE TJ ON SJ.COMCATJOBTYPEID = TJ.JOBTYPEID
LEFT JOIN (SELECT SS.SSSEGMENT, SS.NODEID FROM `EAR-AA-239`.TBLSSSEGMENT S,
`EAR-AA-239`.TBLSSSEGMENT SS WHERE S.SSS = SS.PARENTSSS AND SS.DELETED = 0) TS ON TJ.SSSEGMENT =TS.NODEID
LEFT JOIN `EAR-AA-242`.SEGMENT S ON S.SEGMENTID = D.SEGMENTID
WHERE DATE(J.STARTTIME) > DATE_SUB(DATE(SYSDATE()), INTERVAL 367 DAY)
ORDER BY J.JOBID;
Any help absolutely appreciated!!!

You should specify the datatypes of the columns explicitly. Without that, MySQL has to figure out what the types are. When you're using a CASE expression to return the values for a column, it assumes that the column datatype will be the same as the type of the first THEN value, but this will be wrong if other cases return a different type. In your code, you have some CASE expressions where the first result is DOUBLE, but another result is a CHAR string that can't be converted to DOUBLE.
So it should be
CREATE TABLE ODS.JOB_LOCATION_IDISTRICT (
JOBID VARCHAR(30),
DISTRICTID INT,
...
) AS
SELECT
...

Related

MySQL query with multiple INNER JOIN returns duplicate entries in the result

I have the following data structure:
There are multiple tables:
I need the following return: sum of balance (sum(a.balance) as pnl) from tabposition.
However, this query returns duplicate results. Can anybody help me with this? Thanks
SET #dt_inicio := '2021-12-01';
SET #dt_fim := '2021-12-09';
select a.data, a.fund, 'CASH-USD' as ticker , 'CASH' as strategy, 'Dolar Cash' as company,
'Others' as type, 'Others' as sector,
sum(a.balance) as pnl from tabposition as a
inner join tablistaativos as c on a.ticker = c.ticker
inner join tabdiautil as d on a.data = d.data_util
inner join tabhistorynav as e on a.data = e.data
inner join tabhistorynav as f on d.data_util_ant = f.data
inner join tabprice as g on a.data = g.data
inner join tabprice as i on d.data_util_ant = i.data
inner join tabhistorynav as j on d.data_util_ant = j.data and a.fund = j.fund
inner join tabfatorx as l on a.data = l.data_pos
where a.data >= #dt_inicio and a.data <= #dt_fim and a.fund = 'TORK FUND' and a.qnt <> 0
and (c.class = 'ACCO' or c.class = 'ACCOUNTING' or c.class = 'SPAC' or c.class = 'ACOES' or
c.class = 'OPCOES' or c.class = 'FUNDO')
and e.official = 'Yes' and e.fund = 'TORK FIA' and f.official = 'Yes' and f.fund = 'TORK FIA'
and g.ticker = 'usdbrl' and i.ticker = 'usdbrl'
and l.cotista = 'TORK FIA'
group by a.data
order by a.data

Update sentence with subquery on MySQL

I have the following sentence, that returns the error
Unknown column targets.ID_TARGET in where clause
and I can't find any solution. Could you guys help?
The proposal is update 'sw_automatic' for each row with the value that th subquery provides (0 or 1)
update bt_pry_targets targets
set targets.sw_automatic = (
(
SELECT (CASE WHEN Task.ID_TP_TASKS_GROUPS = 694 THEN '0' ELSE '1' END) AS TYPE_TASK,
Task.ID_TASK FROM bt_tasks AS Task
INNER JOIN bt_pry_cmp_workflows AS BtCmpWorkflows ON (Task.ID_PRY_CMP_WORKFLOW = BtCmpWorkflows.ID_PRY_CMP_WORKFLOW)
INNER JOIN bt_pry_components AS PryComponent ON (PryComponent.ID_PRY_COMPONENT = BtCmpWorkflows.ID_PRY_COMPONENT )
INNER JOIN bt_components AS Component ON (PryComponent.ID_COMPONENT = Component.ID_COMPONENT)
INNER JOIN bt_pry_targets AS PryTarget ON (PryComponent.ID_TARGET = PryTarget.ID_TARGET)
INNER JOIN bt_flows AS Flows ON (Flows.ID_FLOW = Task.ID_FLOW)
WHERE Flows.SW_END_DEPENDENCE = 1
AND PryTarget.ID_TARGET = targets.ID_TARGET
GROUP BY Task.ID_TASK) )
where targets.sw_automatic is null;
In you subquery the column targets.ID_TARGET in not visible
so you could try using you subquery as a join table for updated
update bt_pry_targets targets
inner join (
SELECT (CASE WHEN Task.ID_TP_TASKS_GROUPS = 694 THEN '0' ELSE '1' END) AS TYPE_TASK,
Task.ID_TASK FROM bt_tasks AS Task
INNER JOIN bt_pry_cmp_workflows AS BtCmpWorkflows ON (Task.ID_PRY_CMP_WORKFLOW = BtCmpWorkflows.ID_PRY_CMP_WORKFLOW)
INNER JOIN bt_pry_components AS PryComponent ON (PryComponent.ID_PRY_COMPONENT = BtCmpWorkflows.ID_PRY_COMPONENT )
INNER JOIN bt_components AS Component ON (PryComponent.ID_COMPONENT = Component.ID_COMPONENT)
INNER JOIN bt_pry_targets AS PryTarget ON (PryComponent.ID_TARGET = PryTarget.ID_TARGET)
INNER JOIN bt_flows AS Flows ON (Flows.ID_FLOW = Task.ID_FLOW)
WHERE Flows.SW_END_DEPENDENCE = 1
AND PryTarget.ID_TARGET = targets.ID_TARGET
GROUP BY Task.ID_TASK
) t on t.PryTarget = targets.ID_TARGET
AND targets.sw_automatic is null
set targets.sw_automatic = t.TYPE_TASK

Case not summing correctly

I am having trouble with my query below
SELECT DATE(jc.`date_in`) DAY,
CASE
WHEN jb.`modified_fr` <> 0 THEN ROUND(SUM(jb.`modified_fr`),1)
ELSE ROUND(SUM(jd.`fr1`),1)
END AS AmountOfHoursBooked
,ds.`name` AS dealership, d.`name` AS Department
FROM jobcard jc
LEFT JOIN job jb
ON jc.`id` = jb.`jobcard`
LEFT JOIN job_definition jd
ON jb.`job_definition` = jd.`id`
LEFT JOIN department d
ON jc.`department` = d.`id`
JOIN dealership ds
ON d.`dealership` = ds.`id`
WHERE MONTH(jc.`date_in`) = MONTH(CURRENT_DATE())
AND YEAR(jc.`date_in`) = YEAR(CURRENT_DATE())
AND jd.`fr1` <> 0
AND jc.`status` <> 5
GROUP BY DATE(jc.`date_in`),jc.`department`;
what i need it to do is if the case comes back true it should use that modified fr instead of the original fr from jb table ?
what am I missing ?
thanks in advance

Mysql doesn't recognize proper execution plan

I'm building a stored procedure for an ETL. With in the stored proc a table is created and the same table is used in the next query as two instances(using the same table with two aliases). Since the second query takes absurd amount of time I looked at the execution plans and executed the queries without the stored proc. When executed without the stored proc second query runs as expected in a reasonable amount of time.
Here are the two queries.
Query_1:
CREATE TABLE TMPRPT_STBDEX_SALE_BDM_$tblname (
SALE_JOURNAL_ID BIGINT(20) NULL DEFAULT NULL,
DEBTOR_CONSULTANT_RELATIONSHIP_ID INT(11) NULL DEFAULT '0',
DISPLAY_ORDER INT(11) NULL DEFAULT NULL,
INDEX IDX_SALE_JOURNAL_ID (SALE_JOURNAL_ID),
INDEX IDX_DEBCONS_ID (DEBTOR_CONSULTANT_RELATIONSHIP_ID),
INDEX IDX_DISPLAY_ORDER (DISPLAY_ORDER)
)
ENGINE=InnoDB
;
INSERT INTO TMPRPT_STBDEX_SALE_BDM_$tblname
SELECT DISTINCT
TSS.SALE_JOURNAL_ID,
RDC.DEBTOR_CONSULTANT_RELATIONSHIP_ID,
RDC.DISPLAY_ORDER
FROM
TMPRPT_STBDEX_SALE_BOOKING_$tblname TSS
LEFT OUTER JOIN BOOKING RB
ON (RB.BOOKING_ID = TSS.BOOKING_ID)
LEFT OUTER JOIN BOOKING_DEPT_LEVELS BDL
ON (BDL.BOOKING_ID = RB.BOOKING_ID)
LEFT OUTER JOIN TMPRPT_STBDEX_SEGMENT_$tblname RS
ON (RS.SEGMENT_ID = TSS.SEGMENT_ID)
LEFT OUTER JOIN DEBTOR_CONSULTANT_RELATIONSHIP RDC
ON (RDC.DEBTOR_ID = RB.DEBTOR_ID AND
RDC.CONSULTANT_ID IS NOT NULL AND
RDC.CONSULTANT_TYPE_CODE = 'BUSINESS_DEVELOPMENT' AND
RDC.COMMISSION_PERCENTAGE IS NOT NULL AND
(RDC.DOMESTIC_INTERNATIONAL_CODE = 'BOTH' OR CASE WHEN RDC.DOMESTIC_INTERNATIONAL_CODE = 'DOMESTIC' THEN 1 = RS.IDT_NUMBER ELSE 1 <> RS.IDT_NUMBER END ) AND
RDC.START_DATE <= TSS.TRANSACTION_DATE AND
(RDC.FINISH_DATE IS NULL OR RDC.FINISH_DATE >= TSS.TRANSACTION_DATE))
LEFT OUTER JOIN COST_CENTRE_DEBTOR_CONSULTANT_RELATIONSHIP CCDCR
ON (CCDCR.DEBTOR_CONSULTANT_RELATIONSHIP_ID = RDC.DEBTOR_CONSULTANT_RELATIONSHIP_ID AND CCDCR.COST_CENTRE_ID = RB.COST_CENTRE_ID)
LEFT OUTER JOIN DEPARTMENT_DEBTOR_CONSULTANT_RELATIONSHIP DDCR
ON (DDCR.DEBTOR_CONSULTANT_RELATIONSHIP_ID = RDC.DEBTOR_CONSULTANT_RELATIONSHIP_ID AND
(DDCR.DEPARTMENT_ID = BDL.LEVEL0 OR
DDCR.DEPARTMENT_ID = BDL.LEVEL1 OR
DDCR.DEPARTMENT_ID = BDL.LEVEL2 OR
DDCR.DEPARTMENT_ID = BDL.LEVEL3 OR
DDCR.DEPARTMENT_ID = BDL.LEVEL4 OR
DDCR.DEPARTMENT_ID = BDL.LEVEL5))
WHERE
(RDC.DISPLAY_ORDER = 1 OR RDC.DISPLAY_ORDER = 2) AND
(RDC.HAS_ALL_PERMISSION = 'Y' OR
(CCDCR.COST_CENTRE_ID IS NOT NULL AND DDCR.DEPARTMENT_ID IS NOT NULL));
Query_2:
SELECT
RSAL.SALE_JOURNAL_ID,
RS.COSTING_ID,
RD.DEBTOR_CODE,
CONCAT('B.',LPAD(CAST(RB.BOOKING_ID AS CHAR),10,'0')) AS BOOKING_REFERENCE,
RS.SEGMENT_ID,
DOC.DOCUMENT_REF_NUMBER AS INVOICE_NO,
RCON.NAME AS CONSULTANT_NAME,
COALESCE(RSPS.LEAD_PASSENGER_NAME, RCL.PROFILE_NAME) AS COSTING_PASSENGER,
RBR.CODE AS BRANCH_CODE,
RS.SEGMENT_SHORT_CODE,
(CASE WHEN RS.IDT_NUMBER = 1 THEN
'D'
WHEN RS.IDT_NUMBER = 2 THEN
'T'
WHEN RS.IDT_NUMBER = 3 THEN
'I'
ELSE NULL
END) AS DOM_INT,
(CASE WHEN RSAL.COSTING_PAYMENT_TYPE_CODE = 'PAY_DIRECT' THEN 0 ELSE
RSAL.SUPPLIER_RATES_EXCL_GST +
RSAL.SUPPLIER_RATES_GST_FREE +
RSAL.SUPPLIER_CHARGES_EXCL_COMMISSION +
RSAL.SUPPLIER_CHARGES_COMMISSION_FREE +
RSAL.SUPPLIER_FEES_EXCL_GST +
RSAL.TAX_AMOUNT_EXCL_GST_CALCULATED +
RSAL.TAX_AMOUNT_GST_FREE +
RSAL.AGENCY_MARKUP_EXCL_GST_CALCULATED +
RSAL.AGENCY_DISCOUNT_EXCL_GST_CALCULATED
END) AS GROSS_SALES,
(CASE WHEN RSAL.COSTING_PAYMENT_TYPE_CODE = 'PAY_DIRECT' THEN
RSAL.SUPPLIER_RATES_EXCL_GST +
RSAL.SUPPLIER_RATES_GST_FREE +
RSAL.SUPPLIER_CHARGES_EXCL_COMMISSION +
RSAL.SUPPLIER_CHARGES_COMMISSION_FREE +
RSAL.SUPPLIER_FEES_EXCL_GST +
RSAL.TAX_AMOUNT_EXCL_GST_CALCULATED +
RSAL.TAX_AMOUNT_GST_FREE +
RSAL.AGENCY_MARKUP_EXCL_GST_CALCULATED +
RSAL.AGENCY_DISCOUNT_EXCL_GST_CALCULATED
ELSE 0 END) AS PD_SALES,
(CASE WHEN RSAL.COSTING_PAYMENT_TYPE_CODE = 'PAY_DIRECT' THEN 0 ELSE RSAL.SERVICES_CREDITOR_COMMISSION_AMOUNT_EXCL_GST_CALCULATED - (RS.COSTING_MERCHANT_FEE_POSTED_EXCL_GST * (SIGN(RSAL.SERVICES_CREDITOR_COMMISSION_AMOUNT_EXCL_GST_CALCULATED + RSAL.SUPPLIER_RATES_EXCL_GST))) END) AS EARNED_COMM,
(CASE WHEN RSAL.COSTING_PAYMENT_TYPE_CODE = 'PAY_DIRECT' THEN RSAL.SERVICES_CREDITOR_COMMISSION_AMOUNT_EXCL_GST_CALCULATED - (RS.COSTING_MERCHANT_FEE_POSTED_EXCL_GST * (SIGN(RSAL.SERVICES_CREDITOR_COMMISSION_AMOUNT_EXCL_GST_CALCULATED + RSAL.SUPPLIER_RATES_EXCL_GST))) ELSE 0 END) AS PD_COMM,
RSAL.OVERRIDE_AMOUNT_POSTED_EXCL_GST AS OVERRIDE_COMM,
(CASE
WHEN RDMF.DEBTOR_MANAGEMENT_FEE_ID IS NULL THEN 0
WHEN RDMF.FEE_AMOUNT_TYPE = 'PERCENTAGE'
THEN
(RDMF.FEE_AMOUNT / 100.00) *
(RSAL.SUPPLIER_RATES_EXCL_GST +
RSAL.SUPPLIER_RATES_GST_FREE +
RSAL.SUPPLIER_CHARGES_EXCL_COMMISSION +
RSAL.SUPPLIER_CHARGES_COMMISSION_FREE)
WHEN RDMF.FEE_AMOUNT_TYPE = 'DOLLAR_INCL_GST'
THEN (RDMF.FEE_AMOUNT / ((100.00 + RAGN.GST_PERCENTAGE) / 100.00))
ELSE
RDMF.FEE_AMOUNT
END) AS RETENTIONS,
(RS.COSTING_SPECULATIVE_MERCHANT_FEE_POSTED_EXCL_GST * SIGN(RSAL.SERVICES_CREDITOR_COMMISSION_AMOUNT_EXCL_GST_CALCULATED + RSAL.SUPPLIER_RATES_EXCL_GST)) AS MERCHANT_FEE,
CONS.NAME AS BDM1_NAME,
RDC.COMMISSION_PERCENTAGE AS BDM1_PERCENTAGE,
CONS2.NAME AS BDM2_NAME,
RDC2.COMMISSION_PERCENTAGE AS BDM2_PERCENTAGE
FROM
TMPRPT_STBDEX_SALE_BOOKING_$tblname TSS
LEFT OUTER JOIN SALE_JOURNAL RSAL
ON (RSAL.SALE_JOURNAL_ID = TSS.SALE_JOURNAL_ID)
LEFT OUTER JOIN AGENCY RAGN
ON (RAGN.AGENCY_ID = 1)
LEFT OUTER JOIN TMPRPT_STBDEX_SEGMENT_$tblname RS
ON (RS.COSTING_ID = RSAL.COSTING_ID)
LEFT OUTER JOIN BOOKING RB
ON (RB.BOOKING_ID = RS.BOOKING_ID)
LEFT OUTER JOIN DEBTOR RD
ON (RD.DEBTOR_ID = RB.DEBTOR_ID)
LEFT OUTER JOIN TRANSACTION_JOURNAL RTJ
ON (RTJ.TRANSACTION_JOURNAL_ID = RSAL.TRANSACTION_JOURNAL_ID)
LEFT OUTER JOIN TRANSACTION_JOURNAL_LINKS TJL
ON (TJL.TRANSACTION_JOURNAL_ID = RTJ.TRANSACTION_JOURNAL_ID)
LEFT OUTER JOIN INVOICE RI
ON (RI.INVOICE_ID = TJL.INVOICE_ID)
LEFT OUTER JOIN DOCUMENT DOC
ON (RI.DOCUMENT_ID = DOC.DOCUMENT_ID)
LEFT OUTER JOIN CONSULTANT RCON
ON (RCON.CONSULTANT_ID = RB.PREF_CONSULTANT1_ID)
LEFT OUTER JOIN SEGMENT_PASSENGER_SUMMARY RSPS
ON (RSPS.SEGMENT_ID = RS.SEGMENT_ID)
LEFT OUTER JOIN BRANCH RBR
ON (RBR.BRANCH_ID = RB.LVL1_BRANCH_ID)
LEFT OUTER JOIN CLIENT RCL
ON (RCL.CLIENT_ID = RB.CLIENT_ID)
LEFT OUTER JOIN DEBTOR_MANAGEMENT_FEE RDMF
ON (RDMF.DEBTOR_ID = RD.DEBTOR_ID AND
RDMF.SEGMENT_TYPE = RS.SEGMENT_TYPE_CODE AND
(RDMF.AIRLINE_CODE = RS.AIR_AIRLINE_CODE OR RDMF.SEGMENT_TYPE <> 'TICKET') AND
(RDMF.INT_DOM = CASE WHEN RS.IDT_NUMBER = 1 THEN 'DOMESTIC' ELSE 'INTERNATIONAL' END) AND
(RDMF.TERMINATION_DATE IS NULL OR RDMF.TERMINATION_DATE > CURDATE()))
LEFT OUTER JOIN TMPRPT_STBDEX_SALE_BDM_$tblname TSSB
ON (TSSB.SALE_JOURNAL_ID = RSAL.SALE_JOURNAL_ID AND TSSB.DISPLAY_ORDER = 1)
LEFT OUTER JOIN DEBTOR_CONSULTANT_RELATIONSHIP RDC
ON (RDC.DEBTOR_CONSULTANT_RELATIONSHIP_ID = TSSB.DEBTOR_CONSULTANT_RELATIONSHIP_ID AND
(RDC.CONSULTANT_ID = ParamBDMConsultant OR ParamBDMConsultant IS NULL))
LEFT OUTER JOIN CONSULTANT CONS ON (CONS.CONSULTANT_ID = RDC.CONSULTANT_ID)
LEFT OUTER JOIN TMPRPT_STBDEX_SALE_BDM_$tblname TSSB2
ON (TSSB2.SALE_JOURNAL_ID = RSAL.SALE_JOURNAL_ID AND TSSB2.DISPLAY_ORDER = 2)
LEFT OUTER JOIN DEBTOR_CONSULTANT_RELATIONSHIP RDC2
ON (RDC2.DEBTOR_CONSULTANT_RELATIONSHIP_ID = TSSB2.DEBTOR_CONSULTANT_RELATIONSHIP_ID AND
(RDC2.CONSULTANT_ID = ParamBDMConsultant OR ParamBDMConsultant IS NULL))
LEFT OUTER JOIN CONSULTANT CONS2 ON (CONS2.CONSULTANT_ID = RDC2.CONSULTANT_ID)
WHERE
(ParamBDMConsultant IS NULL OR RDC.CONSULTANT_ID = ParamBDMConsultant) AND
(ParamExcludeCostingsWithoutBDM = 'No' OR RDC.CONSULTANT_ID IS NOT NULL)
GROUP BY
RSAL.SALE_JOURNAL_ID;
Note that TMPRPT_STBDEX_SALE_BDM_$tblname created in Query_1 is used twice in Query_2.
Below are the execution plans for Query_2
Execution Plan for Query_2 when executed with in stored proc
Execution Plan for Query_2 when executed manually with out stored proc
Note the highlighted lines where Table created in Query_1 is involved. I don't understand why it's scanning the entire table when type is ref and proper index is identified.
I was able to get this resolved by changing how the index is created for table in Query_1 to an Alter table add index index_name after the table is populated, and that solved my problem.
Also able to get this resolved by separating the data set in Query_1 into two tables and use them in place of the single table in Query_2.
For me it seemed like mysql doesn't pick the proper execution plan due to a delay in gathering stats.
Can someone explain why this is happening?
Mysql version: 5.6

DATEDIFF Subquery returns more than 1 row in mysql

Having an issue with a specific section of a query using DATEDIFF:
select 1 as NumApps,
LenderInfo.Name as LenderName,
CASE WHEN ApplicationInfo.AEType IS NULL OR ApplicationInfo.AEType = 0 THEN 'Unknown' ELSECONCAT (AEContact.FirstName, ' ', AEContact.LastName) END As AEName,
CASE WHEN b.createdby > 0 THEN CONCAT (contactinfo.firstname, ' ', contactinfo.lastname) END AS LogActionBy,
CASE WHEN ApplicationInfo.RecertificationById IS NULL THEN CASE WHEN ApplicationInfo.IsCorrespondent IS NULL OR ApplicationInfo.IsCorrespondent = 0 THEN 'Wholesale' ELSE 'Correspondent' END ELSE CASE WHEN ApplicationInfo.IsCorrespondent IS NULL OR ApplicationInfo.IsCorrespondent = 0 THEN 'Wholesale - Recert' ELSE 'Correspondent- Recert' END END As AppType,
Applicationinfo.SubmissionDate,
ApplicationInfo.ApplicationID,
b.status AS LogStatus,
b.CreatedOn as LogDate,
companyinfo.Name,
companyinfo.NMLSEntityID,
applicationinfo.CreatedDate,
ApplicationInfo.Status as ApplicationStatus,
ApplicationInfo.StatusChangeDate,
DATEDIFF ((Select CreatedOn From ApplicationStatusChangeLog a where a.ApplicationId = b.ApplicationId
And a.status = 'Approved'),(Select CreatedOn From ApplicationStatusChangeLog a Where a.ApplicationId = b.ApplicationId And a.status = 'Pending Approval')) AS DaysToApprove
from applicationinfo
INNER JOIN CompanyInfo ON(ApplicationInfo.CompanyId = CompanyInfo.CompanyId)
left join CompanyInfo As LenderInfo ON (ApplicationInfo.LenderId = LenderInfo.CompanyId)
LEFT JOIN UserInfo ON (UserInfo.UserId = ApplicationInfo.LastModifiedById)
LEFT JOIN ContactInfo ON UserInfo.ContactId = ContactInfo.ContactId
LEFT JOIN ContactInfo AS Comergence ON(ApplicationInfo.ComergenceRepId = Comergence.ContactId)
LEFT JOIN UserInfo AS AEUser ON(AEUser.UserId = ApplicationInfo.AEType)
left join paymentinfo on applicationinfo.applicationid = paymentinfo.applicationid
Inner join applicationstatuschangelog b on applicationinfo.applicationid = b.applicationid
LEFT JOIN ContactInfo AS AEContact ON(AEContact.ContactId = AEUser.ContactId)
LEFT JOIN UserInfo AS StatusUser ON(StatusUser.UserId = ApplicationInfo.StatusChangeById)
LEFT JOIN ContactInfo AS StatusContact ON(StatusContact.ContactId = StatusUser.ContactId)
LEFT JOIN ApprovalStatus ON(ApplicationInfo.ApplicationId = ApprovalStatus.ApplicationId AND ApplicationInfo.CompanyId = ApprovalStatus.CompanyHQId
AND ApplicationInfo.CompanyId = ApprovalStatus.CompanyId)
Where ApplicationInfo.Status NOT In ('Approved Monitor Only')
AND LenderInfo.ActiveLenderContract = 1
AND COALESCE(ApplicationInfo.IsDeleted,0) <> 1
AND b.Status NOT IN ('Incomplete', 'Not Submitted')
Group BY b.ApplicationID`
I've seen some people mentioning using IN instead of = within the subquery, but I can't seem to get it to work. Any ideas out there? Thanks in advance.
I was able to get the query working by adding 'Limit 1' after the identified status:
(Select CreatedOn From ApplicationStatusChangeLog a where a.ApplicationId = b.ApplicationId
And a.status = 'Approved' LIMIT 1),(Select CreatedOn From ApplicationStatusChangeLog a Where a.ApplicationId = b.ApplicationId And a.status = 'Pending Approval' LIMIT 1)