I have 3 tables:
'PartNumber' with unique ID 'Part Number' and several fields like 'Description' and 'Workflow Status' ID :
'Part Number' 'Description' WorkflowStatus'
ZU0000 RES 1K 1% 4
ZU0001 RES 2K 1% 2
ZU0002 CAP 10nF 10V 3
...'WorkFlowStatus' with 'ID' and 'Workflows Status' being the text associated to 'PartNumber.Workflow Status':
'ID' 'Workflows Status'
1 New
2 Verified
3 Approved
4 Modified
...'LogWorkflow' which corresponds to a logger of all the actions made on 'PartNumber' but also several other types, identified by 'Type' and 'Reference' i.e. for a 'PartNumber', 'Type'='PN' and 'Reference' = 'PartNumber'.'Part Number' (ZUxxx):
'ID' 'Reference' 'Type' 'Recipient' 'Date' 'PrevStatus' 'NextStatus'
1 'ZU0000' PN Robert 2023.12.01 2 4 #
2 'ZU0001' PN John 2023.10.02 NULL 1
3 'ZU0001' PN Librarian1 2023.10.04 1 2 #
4 'CR06031K00' MPN Mitch 2023.11.04 2 3
5 'ZU0002' PN Robert 2023.12.01 NULL 1
6 'QFN100-200' Footprint Mitch 2024.01.08 NULL 1
7 'ZU0002' PN Librarian1 2024.01.10 1 2
8 'ZU0002' PN Librarian2 2024.01.10 2 3 #
9 'QFN100-200' Footprint Mitch 2024.01.11 NULL 1
I want to link the 'PartNumber' table with 'WorkFlowStatus' and 'LogWorkflow' having the last logged ID in the 'LogWorkflow' table for the PN Type.
These ID are pointed by the 3 # for the 3 Part Number listed
I made this request but this is very very slow. Is there a way to optimize it ?
SELECT
`PartNumber`.`Part Number`, `PartNumber`.`Description`,
`WorkflowStatus`.`Workflow Status`,
LW.`N°`, LW.`Recipient`
FROM `PartNumber`
LEFT JOIN `WorkflowStatus` ON `PartNumber`.`WorkflowStatus`=`WorkflowStatus`.`ID`
LEFT JOIN (
SELECT LW1.`Type`, LW1.`Reference`, LW1.`N°`, LW1.`Recipient` FROM `LogWorkflow` LW1
INNER JOIN (SELECT MAX(`N°`) AS`MAXNUM` FROM`LogWorkflow` WHERE `Type`='PN' GROUP BY `Reference`)
AS LW2 ON LW1.`N°` = LW2.`MAXNUM`)
LW ON `PartNumber`.`Part Number` = LW.`Reference`
The Sub query in the left join is very fast but when associated to the part number table with left join it's very slow
I checked several topics in stackoverflow to write this SQL query which actually works but slowly