我需要使用 WHERE 语句进行更新查询,但如果记录不存在,则应插入数据。
例如更新表 SET this = 'that', that = 'this' WHERE this = 'this' AND that = 'that'
我没有唯一的值,我有 2 列不能出现 2 次或更多次。让我举个例子:
我有一张 table :
Column1 | Column2 | Column3
---------------------------
1 | 2 | 500
1 | 3 | 500 This is OK because column2 is other than above
2 | 2 | 500 ALSO OK because column1 is other than above!
1 | 2 | 500 NOT OK! Already exists -> need update for Column3! needs to be 1000 now!
正如您在表中看到的,这两列可以出现多次!
有这个功能吗?还是先查一下有没有记录?我没有唯一 key
,因此无法使用 this .
最佳答案
这样做 首先触发选择查询
select column_name from table where condition
并使用 mysqli_num_rows 函数对获取数据行进行计数,如果条件错误,则数据集行数将为零,如果数据已获取,则数据集行数将为 1。 所以你现在要做的就是像下面的演示代码一样
$no_rows=mysqli_num_rows(..);
if($no_rows==1)
{
update query;
}
else
{
insert query;
}
这意味着如果行数为1,它将更新它,否则它将插入数据。
关于php - 存在时更新查询,不存在时插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33871657/