1

我有三个表,productsvariantsdata

每个产品都有它自己的productcode。产品可以有任意数量的变体,包括没有变体。变体有自己的代码variantcode。产品有一个productid列,每个变体都有一个相关的productid列。

我想要所有代码的列表,但我只关心productcode产品是否没有变体。否则我想要variantcode. 我写了这个查询来得到这个列表:

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

此查询按我的预期工作。

data表包含每个代码的额外数据。我想将此数据加入此列表。我试过这个查询:

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

但我收到错误“'on 子句'中的未知列'代码'”。我认为这与code生成值有关,所以我尝试了这个查询:

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

此查询有效,但花费了很长时间(约 20 秒,而第一次查询 <1 秒)。ON 子句中的 IFNULL 是问题吗?我怎样才能加快速度?

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桌子两次,如下所示:

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 回答