我創建了一個標量函式,它計算將兩列的值相乘并將結果存盤在一個變數中。該變數被回傳。我的目標是在插入陳述句中使用我的函式,以便使用回傳值填充欄位。我的問題是,當我像這樣呼叫我的函式 select calculate_price(4,5) 時,我得到了想要的結果。但是,當我在插入陳述句中呼叫函式時,我得到了意想不到的結果。
我的代碼如下所示:
CREATE DEFINER=`root`@`localhost` FUNCTION `calculate_price`(idcart int, idProduct int) RETURNS int
DETERMINISTIC
BEGIN
select price*quantity into @price
from product inner join test_product_quantity_cart
on product.id_product=test_product_quantity_cart.id_product
where id_cart=idcart and test_product_quantity_cart.id_product=idProduct;
RETURN @price;
END
我的表 test_product_quantity_cart 中的一行如下所示:
id_cart=4
quantity=5
id_product=2
price_product= -- expected 20
我的表產品中的相關行如下所示:
id_product=2
price=4
如果我以這種方式呼叫我的函式 select calculate_price(4,2),我得到 20。這是有道理的,因為 id 為 2 的產品的價格是 4。數量是 5,所以 4*5=20。但是,當我在插入陳述句中使用該函式以創建一個新行時,如下所示:
insert into test_product_quantity_cart(id_cart,quantity,id_product,price_product )
values (4,5,2, calculate_price(4,2))
我得到 45。我想知道我做錯了什么導致這種不一致的行為。謝謝您的幫助。
uj5u.com熱心網友回復:
當您進行插入時,呼叫函式時尚未寫入資料庫,并且該函式可能會在 test_product_quantity_cart 中找到預先存在的行,因此使用 akina 提供的小提琴并將第一個插入更改為 4/10/2 第二個插入計算價格為 40。此外,第一個插入不獲取價格。
在我看來,無論如何,觸發器會更合適。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442565.html
