如果不存在则插入 其他更新?

INSERT IF NOT EXISTS ELSE UPDATE?(如果不存在则插入 其他更新?)
本文介绍了如果不存在则插入 其他更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于经典的如何插入新记录或更新已存在的记录",我找到了一些可能"的解决方案,但我无法让其中任何一个在 SQLite 中工作.

I've found a few "would be" solutions for the classic "How do I insert a new record or update one if it already exists" but I cannot get any of them to work in SQLite.

我有一个表定义如下:

CREATE TABLE Book 
ID     INTEGER PRIMARY KEY AUTOINCREMENT,
Name   VARCHAR(60) UNIQUE,
TypeID INTEGER,
Level  INTEGER,
Seen   INTEGER

我想做的是添加一个具有唯一名称的记录.如果名称已存在,我想修改字段.

What I want to do is add a record with a unique Name. If the Name already exists, I want to modify the fields.

有人能告诉我怎么做吗?

Can somebody tell me how to do this please?

推荐答案

看看 http://sqlite.org/lang_conflict.html.

你想要这样的东西:

insert or replace into Book (ID, Name, TypeID, Level, Seen) values
((select ID from Book where Name = "SearchName"), "SearchName", ...);

请注意,如果该行已存在于表中,则任何不在插入列表中的字段都将设置为 NULL.这就是 ID 列有一个子选择的原因:在替换情况下,语句会将其设置为 NULL,然后分配一个新的 ID.

Note that any field not in the insert list will be set to NULL if the row already exists in the table. This is why there's a subselect for the ID column: In the replacement case the statement would set it to NULL and then a fresh ID would be allocated.

如果您想在替换案例中的行保留特定字段值但在插入案例中将该字段设置为 NULL,则也可以使用此方法.

This approach can also be used if you want to leave particular field values alone if the row in the replacement case but set the field to NULL in the insert case.

例如,假设您想单独保留 Seen:

For example, assuming you want to leave Seen alone:

insert or replace into Book (ID, Name, TypeID, Level, Seen) values (
   (select ID from Book where Name = "SearchName"),
   "SearchName",
    5,
    6,
    (select Seen from Book where Name = "SearchName"));

这篇关于如果不存在则插入 其他更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)
Inserting NaN value into MySQL Database(将NaN值插入MySQL数据库)
How to get insertId for MySQL using Mysql2 in Node with async and pool?(如何在带异步和池的Node中使用Mysql2获取MySQL的InsertID?)
Window functions not working in pd.read_sql; Its shows error(窗口函数在pd.read_sql中不起作用;它显示错误)
(Closed) Leaflet.js: How I can Do Editing Geometry On Specific Object I Select Only?((已关闭)Leaflet.js:如何仅在我选择的特定对象上编辑几何图形?)