我有一个存储函数需要 select ... from ... where foo IN (select ...)
问题是,与做一个简单的 where = ...
既然这种语法很慢,有没有可能将结果存储到一个变量中,然后在 IN ()
而不是条件?我不知道如何将包含多行的查询存储到一个变量中。
这是使用变量的快速等式(但错误的b/c它只执行1个值而不是多个值)
BEGIN
DECLARE average DECIMAL(10,4);
DECLARE skuAsin VARCHAR(30);
SET skuAsin = (SELECT DISTINCT asin FROM inventory WHERE sku = aSku ORDER BY id DESC LIMIT 1);
SET average = (
SELECT avg(unitsByDay) FROM (
SELECT i.date, sum(units_ordered) as unitsByDay from inventory i
WHERE
i.asin = skuAsin &&
i.marketplace_id = mid &&
i.date between d1 and d2
GROUP BY date
) as vel
);
RETURN average;
END;
这就是慢用 IN (select)
```
BEGIN
DECLARE average DECIMAL(10,4);
SET average = (
SELECT avg(unitsByDay) FROM (
SELECT i.date, sum(units_ordered) as unitsByDay from inventory i
WHERE
i.asin IN (SELECT DISTINCT asin FROM inventory WHERE sku = aSku) &&
i.marketplace_id = mid &&
i.date between d1 and d2
GROUP BY date
) as vel
);
RETURN average;
END;
1条答案
按热度按时间hsgswve41#
而不是
尝试使用
EXISTS
.(我以为
asku
是变量,可能是过程的参数。如果没有,则使用正确的表别名对其进行限定。)在上创建索引
inventory (asin, sku)
来支持它。另一个需要考虑的指标是
inventory (marketplace_id, date, asin)
对于外部查询。