我如何用SQL检查变量是否存在于表中


How can I check with SQL if variable is exist in table

我正在创建函数(PHP),它必须每隔几个小时运行一次并更新一些DB表。1. 如果行不存在- INSERT新行2. 如果行存在- UPDATE当前行

我想用最简单的方式来写因为我要对几个表做

使用insert . . . on duplicate key update语句:

insert into dbtable(cols, . . . )
    select <values here >
    on duplicate key update col2 = values(col2), col3 = values(col3);

在这里有文档。

编辑:

假设你有一些关于动物的唯一键,你的查询看起来像这样:

insert into animals(animal_id, animal_name)
    select @animal_id, @animal_name
    on duplicate key update animal_name = values(animal_name);