I need to join some tables by product id, the problem is that some products in different tables are not written in full format (full format is 12 digits whereas in some cases the same product is written with only the last 6 digits).
I tried to compare by the last 6 digits with length(product_id,6) but it's not a pure comparison due to some products sharing the same last 6 digits but they are not the same.
I tried to perform a check of the length of the product id and only, in that case, take compare the last 6 digits the result are reliable but it working too slowly.
Methode 1: normal join fetch in 30-100 ms
SELECT * FROM
table_a ta
JOIN table_b tb ON ta.product_id = tb.product_id
Methode 2: join by last 6 digits fetch in 100-200 ms but ~10% are fake join
SELECT *
FROM table_a ta
JOIN table_b tb ON right(ta.product_id,6) = right(tb.product_id,6)
Methode 3: join by last 6 digits only if the length of product id is not equal,data is reliable but fetch around 30 seconds
SELECT *
FROM table_a ta
JOIN table_b tb ON
CASE
WHEN LENGTH(ta.product_id) <> LENGTH(tb.product_id)
THEN right(ta.product_id,6) = right(tb.product_id,6)
ELSE ta.product_id = tb.product_id
END
Why does using case conditions make it so slow? How do you suggest I compare those tables? I'm pretty sure there is another method that is not familiar to me yet.