gpt4 book ai didi

PHP Mysql 字段值基于另一个字段值

转载 作者:行者123 更新时间:2023-11-29 20:58:39 24 4
gpt4 key购买 nike

不知道如何问这个问题,但我有一个产品及其价格的数据库。价格由 3 列组成(当前价格、折扣价格、先前价格)。

我使用 fgetcsv() 读取新记录的 CSV,然后使用下面的 Mysqli 查询将新记录插入或更新到我的数据库:

$query = "INSERT INTO products (prodname,currprice,prevprice,discprice) VALUES ('$EachRow[0]','$EachRow[1]','$EachRow[2]','$EachRow[3]') ON DUPLICATE KEY UPDATE currprice='$EachRow[1]';";

问题出在现有产品上。我只想在它们的 prevprice 与 currprice 不同时更新它们的 currprice,并且要更新它们,必须使用新的 currprice。我希望 mysqli 中有类似的东西

"UPDATE IF $EachRow[1]<>currprice SET prevprice=currprice,currprice='$EachRow[1]'"

基本上,对于现有记录,如果当前价格已更改,我希望在将 currprice 更新为新的 $EachRow[1] 之前将之前的 currprice 记录为 prevprice。

有办法实现这一点吗?我们可以在 mysqli 查询中使用 IF 语句吗?

最佳答案

是的,您可以使用IF Duplicate Key Update 之后的子句

INSERT INTO tbl (name, some_column, some_other)
VALUES (username, some_data)
ON DUPLICATE KEY UPDATE
some_other = IF(some_other > somevalue, "in_case_if_cond_is_true", "in_case_if_cond_is_false")

这些被称为 Flow Control Operators , MariaDB 控制流程 Knowledge Base

根据玛丽亚数据库

IF(expr1,expr2,expr3)

If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3

关于PHP Mysql 字段值基于另一个字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37413677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com