mysql插入重复的FIELD而不是KEY

pep*_*600 19 mysql field insert duplicates

-------------------------------------
| user_id | user_name | user_visits |
-------------------------------------
| 1       | foo       | 5           |
-------------------------------------
| 2       | bar       | 12          |
-------------------------------------

user_id:auto increament,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语句实现此目的?

Wes*_*Wes 5

当然有,但这与您的insert陈述无关。您需要在user_name列上添加唯一索引:

create unique index user_name_idx on yourtable (user_name);
Run Code Online (Sandbox Code Playgroud)

然后在跟踪计数的代码中,必须决定是进行插入还是更新。


Vij*_*jay 5

您必须为用户名字段创建密钥,然后使用INSERT ON DUPLICATE查询来更新列值.

例如,您的查询必须是,

   INSERT INTO table (user_name) VALUES ('baz'), ('bar'), ('qux') 
   ON DUPLICATE KEY UPDATE user_visits=user_visits+1;
Run Code Online (Sandbox Code Playgroud)

如需进一步参考,请访问http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

  • 好的,但是如果需要与2个键进行比较,例如:agency和user_name阻止新行并改为更新? (2认同)