如何在不存在的地方进行插入?
我想将插入查询与“不存在的地方”结合起来,以免违反 PK 约束。但是,如下所示的语法给我带来了 关键字 'WHERE' 附近的语法不正确
错误 -
INSERT INTO myTable(columns...)
VALUES(values...)
WHERE NOT EXISTS
(SELECT *
FROM myTable
WHERE pk_part1 = value1,
AND pk_part2 = value2)
我该如何实现此目的?
(一般来说,可以将 insert 与 where 子句结合起来吗?)
I'd like to combine an insert query with a "where not exists" so as not to violate PK constraints. However, syntax such as the following gives me an Incorrect syntax near the keyword 'WHERE'
error -
INSERT INTO myTable(columns...)
VALUES(values...)
WHERE NOT EXISTS
(SELECT *
FROM myTable
WHERE pk_part1 = value1,
AND pk_part2 = value2)
How can I accomplish this?
(In general, can you combine an insert with a where clause?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:
阅读马丁斯链接后,如果承认,最好的解决方案是:
Edit:
After reading martins link, If admit, that the best solution is:
保留唯一值列表的最简单方法是 a) 将列设置为主键或 b) 在列上创建唯一约束。当尝试插入/更新表中已存在的值时,其中任何一个都会导致错误,当 NOT EXISTS/etc 会默默失败时——没有错误,查询将正确执行。
也就是说,使用 INSERT/SELECT(不包括 VALUES 部分):
The simplest way to keep a unique list of values is to either a) set the column(s) as the primary key or b) create a unique constraint on the column(s). Either of these would result in an error when attempting to insert/update values to something that already exists in the table, when a NOT EXISTS/etc would fail silently -- no error, query will execute properly.
That said, use an INSERT/SELECT (don't include the VALUES portion):
这些例子都不适合我......所以我建议这个例子:
None of the examples worked for me... so I suggest this example:
mysql 有插入忽略查询:
http://dev.mysql.com/doc/refman/5.0/en /insert.html
ON DUPLICATE KEY UPDATE 也可用
mysql has the insert ignore query:
http://dev.mysql.com/doc/refman/5.0/en/insert.html
ON DUPLICATE KEY UPDATE is also available