我有这样简单的表:
+----------+---------------+-------------+
| ID (int) | KEY (varchar) | VALUE (int) |
+----------+---------------+-------------+
| 1 | asdf | 100 |
| 2 | fdsa | 321 |
| 3 | ecda | 211 |
+----------+---------------+-------------+
我希望更新KEY = 'something'
行,但如果没有KEY = 'something'
行,我想要INSERT
新行:
+----------+---------------+-------------+
| ID (int) | KEY (varchar) | VALUE (int) |
+----------+---------------+-------------+
| 1 | asdf | 100 |
| 2 | fdsa | 321 |
| 3 | ecda | 211 |
| 4 | something | 200 |
+----------+---------------+-------------+
只能在一个查询中使用吗?
答案 0 :(得分:7)
您可以使用ON DUPLICATE KEY UPDATE
INSERT INTO yourtable (`id`, `key`, `value`) VALUES (4, 'something', 200)
ON DUPLICATE KEY UPDATE `value` = 200;
key
列上应该有UNIQUE索引
<强> SQLFiddle 强>
答案 1 :(得分:6)
是的,这很简单。
这就是你要找的东西:
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)