我的MySQL数据库中有一个存储过程,工作正常。
但是,由于我必须在相同的查询中使用相同的参数调用相同的过程3次,如果我可以使用第一次调用的结果而不是后续调用,那么它将是一个不错的性能提升。
编辑:更改了示例,因为它过于简单,误导了回复
我需要表格:产品和价格 - 价格会根据一年中的时间和付款模式而变化,因此结构为:(id,product_id,date_from,date_to,price_mode_1,price_mode_2,price_mode_3)
示例:
我现在所做的是
SELECT products.*,
get_a_quote(products.id,date_to,date_from, quantity_mode_1,quantity_mode_2,quantity_mode_3)
FROM peoducts
WHERE get_a_quote(products.id,date_to,date_from, quantity_mode_1,quantity_mode_2,quantity_mode_3) >0
ORDER BY
get_a_quote(products.id,date_to,date_from, quantity_mode_1,quantity_mode_2,quantity_mode_3)
LIMIT 10
我想做的是
SELECT products.*,
get_a_quote(products.id,date_to,date_from, quantity_mode_1,quantity_mode_2,quantity_mode_3) into quote
FROM peoducts
WHERE quote >0
ORDER BY
quote
LIMIT 10
这可能吗?
* 编辑:功能代码*
FUNCTION `get_a_quote`(`productid` INT, `startDate` SMALLINT, `endDate` SMALLINT, `mode_1_quantity` SMALLINT, `mode_2_quantity` TINYINT, `mode_3_quantity` TINYINT) RETURNS smallint(6)
BEGIN
declare totalprice,p_1,p_2,p_3 smallint;
SELECT price_1,price_2,price_3 into p_1,p_2,p_3 FROM pricing WHERE id=productid and ((startDate between date_from and date_to) and (endDate between date_from and date_to));
if p_3 is null then
set mode_2_quantity=mode_3_quantity+mode_2_quantity;
set mode_1_quantity=mode_1_quantity+(4*mode_3_quantity);
set p_3=0;
set mode_3_quantity=0;
end if;
if p_2 is null then
set mode_1_quantity=mode_1_quantity+(3*mode_2_quantity);
set p_2=0;
set mode_2_quantity=0;
end if;
if mode_1_quantity>0 and p_1 is null then
return 0;
end if;
set totalprice = p_1*mode_1_quantity+p_2*mode_2_quantity)+p_3*mode_3_quantity);
RETURN totalprice;
END
谢谢大家
答案 0 :(得分:1)
您可以在派生表中执行此操作:
SELECT *
FROM (
SELECT customers.*,
totalOrders (customers.id) AS total
FROM customers
) AS t
WHERE total >0
ORDER BY
total
LIMIT 10
但是,我不会为此使用存储函数。它必然会有令人难以置信的糟糕表现。
我使用JOIN,这样我才能获取订单数超过零的客户。
答案 1 :(得分:0)
对我来说,它在语义上看起来就像是在表上添加一个新的依赖列。您可以使用视图:
CREATE VIEW v AS
SELECT customers.*,
get_a_quote(products.id,date_to,date_from, quantity_mode_1,quantity_mode_2,quantity_mode_3) AS total
FROM customers;
然后您可以在查询中使用它:
SELECT *
FROM v
WHERE total >0
ORDER BY
total
LIMIT 10;
但是你的函数正在做的事情可能会更好地在你的表上使用JOIN实现,例如:
SELECT customers.*,
SUM(orders.value)
FROM
customers
JOIN orders ON
customers.id=orders.customer_id
GROUP BY customers.id
HAVING SUM(orders.value) >0
ORDER BY
SUM(orders.value)
LIMIT 10;
你能告诉我们你的功能代码吗?