------------------------------------- | user_id | user_name | user_visits | ------------------------------------- | 1 | foo | 5 | ------------------------------------- | 2 | bar | 12 | -------------------------------------
user_id:自动递增,user_visits:默认1
INSERT INTO table (user_name) VALUES ('baz'), ('bar'), ('qux');
上面的语句当然会插入3条新记录,结果:
------------------------------------- | user_id | user_name | user_visits | ------------------------------------- | 1 | foo | 5 | ------------------------------------- | 2 | bar | 12 | ------------------------------------- | 3 | baz | 1 | ------------------------------------- | 4 | bar | 1 | ------------------------------------- | 5 | qux | 1 | -------------------------------------
但我想要实现的是:
------------------------------------- | user_id | user_name | user_visits | ------------------------------------- | 1 | foo | 5 | ------------------------------------- | 2 | bar | 13 | ------------------------------------- | 3 | baz | 1 | ------------------------------------- | 4 | qux | 1 | -------------------------------------
从字面上看,
如果字段 user_name 存在,则更新 user_visits,否则插入一条新记录。
是否可以通过单个插入语句实现此目的?
最佳答案
当然有,但它与您的 insert
语句无关。您需要在 user_name
列上添加唯一索引:
create unique index user_name_idx on yourtable (user_name);
然后在跟踪计数的代码中必须决定是进行插入还是更新。
关于mysql 在重复的 FIELD 而不是 KEY 上插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5786407/