简体   繁体   English

如果id存在,则更新;否则,插入(ODBC)

[英]UPDATE if id exists, else INSERT (ODBC)

I'm using a PHP script to connect to a microsoft access database using ODBC 我正在使用PHP脚本使用ODBC连接到Microsoft Access数据库

The table I'm working on has an 'id' column. 我正在处理的表有一个“ id”列。 I'd like to INSERT new records if the SKU doesn't already exist, else if the SKU does exist, simply UPDATE that record. 如果SKU不存在,我想插入新记录;否则,如果SKU存在,则只需更新该记录。

What is the correct SQL for this? 正确的SQL是什么? Is it possible to do it in one query? 是否可以在一个查询中完成?

I would rather do it in 2 queries. 我宁愿在2个查询中执行此操作。

For me update or insert they are different BUSINESS logics. 对我而言,更新或插入是不同的业务逻辑。 To get your code clear and clean it's better you explicitly define the logic for INSERT and UPDATE. 为了使代码清晰整洁,最好为INSERT和UPDATE定义逻辑。

And technically I don't see a Clean way doing it in one SQL statement. 从技术上讲,我看不到在一条SQL语句中执行清除的方法。 Each of statement has to start with a "verb" it's either "UPDATE" or "SELECT" or "DELETE" or something else. 每个语句必须以“动词”开头,即“ UPDATE”或“ SELECT”或“ DELETE”或其他形式。 Or if you insist to do so, you can try delete the potential existing one before you are doing "insert", then you do the "insert" anyway, but then maybe you get a inconsistent Id for same entity, which could cause problems too. 或者,如果您坚持要这样做,则可以在执行“插入”操作之前尝试删除潜在的现有对象,然后再进行“插入”操作,但是对于同一实体,您可能会获得不一致的ID,这也可能导致问题。

Or if "id" is primary key, another silly way is to do an "update" anyway, then do "insert" anyway. 或者,如果“ id”是主键,那么另一种愚蠢的方法是无论如何都要进行“更新”,然后无论如何都要进行“插入”。 If there's no valid id, update will fail, and insert will succeed. 如果没有有效的ID,则更新将失败,并且插入将成功。 If there's valid id, update will succeed and insert will fail. 如果有有效的ID,更新将成功,插入将失败。 You'll get it done without the BUSINESS if-else logic, but everytime there'll be a SQL failure, which IS silly and ugly. 您无需使用业务 if-else逻辑就可以完成任务,但是每次都会发生SQL错误,这很愚蠢的事情。

That's pretty much what I can think of. 这就是我能想到的。

Personally, I would leave that to the application logic rather than the database logic. 就个人而言,我将其留给应用程序逻辑而不是数据库逻辑。 You can simply do: 您可以简单地执行以下操作:

if($id)
{
    $sql = 'UPDATE ... WHERE id = ?'; // assuming use of parameterized query
}
else
{
    $sql = 'INSERT INTO ...';
}

I wouldn't suggest doing it in one query. 我不建议在一个查询中这样做。 Check if the value you want to add exists before you do the query to add a new value. 在执行查询以添加新值之前,请检查要添加的值是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM