I have three tables, products
, variants
, and data
.
Each product has it's own productcode
. Products can have any number of variants including none. Variants have their own code variantcode
. Products have a productid
column, and each variant has a related productid
column.
I want a list of all the codes, but I only care about the productcode
if a product has no variants. Otherwise I want the variantcode
. I wrote this query to get this list:
SELECT IFNULL(variants.variantcode, products.productcode) AS code
FROM products
LEFT OUTER JOIN variants ON (products.productid = variants.productid)
ORDER BY code
This query works as I expected.
The data
table contains extra data for each code. I want to join this data onto this list. I tried this query:
SELECT IFNULL(variants.variantcode, products.productcode) AS code
FROM products
LEFT OUTER JOIN variants ON (products.productid = variants.productid)
LEFT OUTER JOIN data ON (data.partno = code)
ORDER BY code
But I get an error "Unknown column 'code' in 'on clause'". I assumed this had something to do with code
being a generated value, so I then tried this query:
SELECT IFNULL(variants.variantcode, products.productcode) AS code
FROM products
LEFT OUTER JOIN variants ON (products.productid = variants.productid)
LEFT OUTER JOIN data ON (data.partno = IFNULL(variants.variantcode, products.productcode))
ORDER BY code
This query worked, but took a long time (~20 seconds vs <1 second for the first query). Is the IFNULL in the ON clause the problem? How can I speed it up?