问题描述
我有一个不时更新数据集的数据库。在这里,可能会交付已存在于数据库中的数据集。
I have a database that is updated with datasets from time to time. Here it may happen that a dataset is delivered that already exists in database.
当前,我首先要做的是
SELECT FROM ... WHERE val1=... AND val2=...
检查是否存在包含这些数据的数据集(使用WHERE语句中的数据)。如果它没有返回任何值,则表示我正在执行INSERT。
to check, if a dataset with these data already exists (using the data in WHERE-statement). If this does not return any value, I'm doing my INSERT.
但这对我来说似乎有点复杂。所以我的问题是:是否有某种条件插入仅在不存在的情况下才添加新数据集?
But this seems to be a bit complicated for me. So my question: is there some kind of conditional INSERT that adds a new dataset only in case it does not exist?
我正在使用
I'm using SmallSQL
推荐答案
您可以
INSERT INTO targetTable(field1)
SELECT field1
FROM myTable
WHERE NOT(field1 IN (SELECT field1 FROM targetTable))
某些关系数据库已针对上述内容改进了语法,因为您所描述的是相当常见的任务。 SQL Server具有 MERGE
语法以及各种选项,而MySQL具有可选的 INSERT或IGNORE
语法。
Certain relational databases have improved syntax for the above, since what you describe is a fairly common task. SQL Server has a MERGE
syntax with all kinds of options, and MySQL has optional INSERT OR IGNORE
syntax.
编辑: 很少实现它实现的SQL标准的哪一部分。它可能不会实现子查询,因此,如果您需要坚持使用SmallSQL,则可能无法遵循上述建议或其他任何建议。
SmallSQL's documentation is fairly sparse as to which parts of the SQL standard it implements. It may not implement subqueries, and as such you may be unable to follow the advice above, or anywhere else, if you need to stick with SmallSQL.
这篇关于是否使用SQL条件插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!