Unique join while keeping the original table mysql

lakesh :

I would like to join three tables in sql. table1 and table2 needs to be joined on the key symbol, however the symbol from table1 need edited before joining.

Three joins:

SELECT table1.symbol, table1.risk_factor, table1.risk_factor_name, table1.type, table1.position, table3.`Position dif ex corr`, table1.haircut
FROM `Positions_EOD` table1
LEFT JOIN `positions1` table2 ON table1.symbol = table2.symbol
LEFT JOIN (SELECT * FROM `Final_Pos` WHERE business_date = '2020-04-01' AND `Position check` = 'Correct') table3 ON table2.isin = LEFT(table3.VT_id, INSTR(table3.VT_id, '_') - 1)
WHERE table1.business_date = '2020-04-01' AND table2.business_date = '2020-04-01' AND table2.legal_entity = 'HK' AND table1.symbol LIKE 'ES%'

Before joining table1, it needs to be edited like this:

SELECT 
CASE
    WHEN (`type` = 'ST') THEN symbol
    WHEN (`type` = 'FU') THEN LEFT(REPLACE(symbol,' ', ''), LENGTH(REPLACE(symbol,' ', ''))-2)
END AS 'symbol'
FROM `Positions_EOD`

How do I edit the table1 join so that symbol from table1 is edited before joining?

forpas :

Use that CASE expression in the ON clause:

SELECT table1.symbol, table1.risk_factor, table1.risk_factor_name, table1.type, table1.position, table3.`Position dif ex corr`, table1.haircut
FROM `Positions_EOD` table1 LEFT JOIN `positions1` table2
ON CASE
    WHEN (table1.`type` = 'ST') THEN table1.symbol
    WHEN (table1.`type` = 'FU') THEN LEFT(REPLACE(table1.symbol,' ', ''), LENGTH(REPLACE(table1.symbol,' ', ''))-2)
END = table2.symbol
..................................

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=395188&siteId=1