SQLite INSERT - 重复键更新 (UPSERT)
MySQL有这样的功能:
INSERT INTO visits (ip, hits)
VALUES ('127.0.0.1', 1)
ON DUPLICATE KEY UPDATE hits = hits + 1;
据我所知SQLite中不存在这个功能,我想知道是否有任何方法可以达到相同的效果而不必执行两个查询。另外,如果这不可能,您更喜欢什么:
- SELECT +(INSERT 或 UPDATE) 或
- UPDATE(+ INSERT 如果 UPDATE 失败)
MySQL has something like this:
INSERT INTO visits (ip, hits)
VALUES ('127.0.0.1', 1)
ON DUPLICATE KEY UPDATE hits = hits + 1;
As far as I know this feature doesn't exist in SQLite, what I want to know is if there is any way to achive the same effect without having to execute two queries. Also, if this is not possible, what do you prefer:
- SELECT + (INSERT or UPDATE) or
- UPDATE (+ INSERT if UPDATE fails)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这要求“ip”列具有唯一(或主键)约束。
编辑:另一个很好的解决方案:https://stackoverflow.com/a/4330694/89771。
This requires the "ip" column to have a UNIQUE (or PRIMARY KEY) constraint.
EDIT: Another great solution: https://stackoverflow.com/a/4330694/89771.
从3.24.0开始SQLite也支持upsert,所以现在你可以简单地编写以下内容
Since 3.24.0 SQLite also supports upsert, so now you can simply write the following
我更喜欢
UPDATE(如果UPDATE失败则+INSERT)
。更少的代码=更少的错误。I'd prefer
UPDATE (+ INSERT if UPDATE fails)
. Less code = fewer bugs.当前的答案仅适用于 sqlite OR mysql (取决于您是否使用 OR )。因此,如果您想要跨 dbms 兼容性,可以执行以下操作...
The current answer will only work in sqlite OR mysql (depending on if you use OR or not). So, if you want cross dbms compatibility, the following will do...
为此,您应该使用 memcached,因为它是存储单个值(访问次数)的单个键(IP 地址)。您可以使用原子增量函数来确保不存在“竞争”条件。
它比 MySQL 更快并节省负载,因此 MySQL 可以专注于其他事情。
You should use memcached for this since it is a single key (the IP address) storing a single value (the number of visits). You can use the atomic increment function to insure there are no "race" conditions.
It's faster than MySQL and saves the load so MySQL can focus on other things.