我有一个存储kmart和walmart产品的数据库。一些kmart和walmart产品是相同的,它存储在匹配的产品表中,记录与其真实股票代码匹配(每个供应商的股票代码是唯一的)。
然而,在当前产品的主表中,该表包含其中的所有产品,并且每次执行搜索时,还会执行对matchedProducts的搜索,以查看查询是否可以提供带有匹配项的产品,一切都是工作正常,除非你看到下面的代码:
SELECT cp.brand, cp.name, cp.quantity, cp.unitPrice, cp.price, cp.stockcode as fakeStockcode,
cp.vendor, pk.stockcode as realStockcode,
(CASE
WHEN (vendor = 1)
THEN
(SELECT walmart FROM matchedProducts mp WHERE realStockcode = mp.kmart)
ELSE
(SELECT kmart FROM matchedProducts mp WHERE realStockcode = mp.walmart)
END) as realMatchingStockcode,
(SELECT productKey FROM productKeys WHERE productKeys.stockcode = realMatchingStockcode) as fakeMatchingStockcode,
(SELECT brand FROM currentProducts WHERE currentProducts.stockcode = fakeMatchingStockcode) as matchingBrand,
(SELECT name FROM currentProducts WHERE currentProducts.stockcode = fakeMatchingStockcode) as matchingName,
(SELECT price FROM currentProducts WHERE currentProducts.stockcode = fakeMatchingStockcode) as matchingPrice,
(SELECT unitPrice FROM currentProducts WHERE currentProducts.stockcode = fakeMatchingStockcode) as matchingUnitPrice
FROM currentProducts cp
LEFT JOIN productKeys pk ON cp.stockcode = pk.productKey
WHERE name LIKE "%coffee%" LIMIT 300
上面的代码非常滞后,这是由于以下部分:
(SELECT brand FROM currentProducts WHERE currentProducts.stockcode = fakeMatchingStockcode) as matchingBrand,
(SELECT name FROM currentProducts WHERE currentProducts.stockcode = fakeMatchingStockcode) as matchingName,
(SELECT price FROM currentProducts WHERE currentProducts.stockcode = fakeMatchingStockcode) as matchingPrice,
(SELECT unitPrice FROM currentProducts WHERE currentProducts.stockcode = fakeMatchingStockcode) as matchingUnitPrice
这四行代码使得查询滞后的次数远远超过它,但是对于从对方供应商那里获取匹配产品的详细信息是必要的。无论如何,重新编写此查询或重组查询以使其更高效和更快?
我不擅长SQL,所以我确信我写得很好,任何帮助都会非常感激!
编辑:示例数据
当前产品表:
Brand | Name | quantity | unitPrice | price | stockcode | vendor
'calidad canon', 'Calidad Canon Printer Ink Pgi-650bk Black', 'each', '$0.00 / 0', '15', 'AAFF', '1'
'Cetaphil', 'Moisturising Bath & Wash', '230mL', '$3.70 per 100mL', '8.5', 'AAVb', '0'
'moki', 'Moki Noise Isolation Earbuds Black Or White', 'each', '$0.00 / 0', '10', 'AAWH', '1'
'lamb leg', 'Lamb Leg Steak Heart Smart', 'min. 300g', '$21.00 / 1KG', '6.3', 'AAiN', '1'
'heinz simply food', 'Heinz Simply Food 6 Months Banana Custard', '120g', '$1.25 / 100G', '1.5', 'AAle', '1'
'aroma essentials', 'Aroma Essentials Candle Lemongrass & Ginger', '300g', '$5.00 / 100G', '15', 'AAuL', '1'
'maybelline great lash big', 'Maybelline Great Lash Big Mascara Blackest Black', '10ml', '$9.05 / 10ML', '9.05', 'AAuX', '1'
匹配产品表:
matchId | walmartProductId | kmartProductId
'1', '9240819P', '380151'
'2', '9224109P', '724631'
'3', '9224153P', '724633'
'4', '7422859P', '322001'
'5', '9088598P', '568518'
'6', '6803008P', '16578'
产品密钥表(记录真实股票代码与生成股票代码的表格):
stockcode | productKey
'7230', 'AAFF'
'2459250P', 'AAVb'
'364440', 'AAWH'
'209458', 'AAiN'
'362691', 'AAle'
'565835', 'AAuL'