1

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?

4

2 に答える 2

1

これを試して:

 select product_variants.code from

 (SELECT IFNULL(variants.variantcode, products.productcode) AS code 
 FROM products 
 LEFT OUTER JOIN variants ON (products.productid = variants.productid) 
 ORDER BY code) 

 as product_variants

 LEFT OUTER JOIN data ON (data.partno = product_variants.code) 
于 2013-01-23T19:20:09.223 に答える
0

data次のように、テーブルに 2 回参加してみてください。

SELECT IFNULL(variants.variantcode, products.productcode) AS code
     , IFNULL(D1.something, D2.something) AS something 
FROM products 
LEFT OUTER JOIN variants
ON (products.productid = variants.productid) 
LEFT OUTER JOIN data as D1
ON (D1.partno = variants.variantcode) 
LEFT OUTER JOIN data as D2
ON (D2.partno = products.productcode) 
ORDER BY code
于 2013-01-23T19:20:21.953 に答える