![](/img/trans.png)
[英]Fastest way to update a MySQL table if row exists else insert. More than 2 non-unique keys
[英]MySql Table Insert if not exist otherwise update on non-unique columns
在这样的表中:
ID | user_ID | name | value
1 | 36 | order | {1, 'asc'}
2 | 36 | colvis | 0,1,2,4,7
3 | 36 | colorder | 0,1,2,4,3,5,6,7
4 | 37 | colvis | 0,1,2,4,5,7
如果只有ID是唯一且是AUTO_INCREMENT的,那么我需要为user_ID = 36和colvis ='something'插入新行,如果该用户的'colvis'行尚不存在,即执行类似'INSERT IF NOT EXIST user_ID = x AND name = y ELSE UPDATE”查询。
例如,如果我有user_ID = 36和name ='colorder',它应该更新第3行,但是当user_ID = 37和name ='colorder'时,它应该插入新行。 与user_ID = 36和name ='filter'相同,它应该插入新行。
可以用
$exist = $sql->Query("SELECT * FROM test WHERE user_ID = 36 AND name='colvis'");
if ($exist) {
//UPDATE
} else {
// INSERT
}
但是,那里没有一线吗?
我查看了插入MySQL表或更新(如果存在)和MySQL过程以创建或更新表中的行以及MySql插入(如果不存在)两列对,否则进行了更新 ,但是除非我有'user_ID'和'name列是唯一的吗?
您正在寻找insert . . . on duplicate key update
insert . . . on duplicate key update
insert . . . on duplicate key update
。 但是首先,您需要一个唯一的索引:
create unique index unq_test_userID_name on test(user_ID, name)
然后,您可以进行插入:
insert into test(user_ID, name, value)
values (36, 'colvis', '3')
on duplicate key update value values(val);
这里有一个很大的警告:在逗号分隔的列表中存储多个值几乎从来都不是正确的事情。 该规则很少有例外,这就是为什么我回答了这个问题。
正确的解决方案可能是联结表TestValues
,每个“测试”一行,每个“值”一行。 在这种情况下,您想做的事情很简单:
insert into TestValues(test_id, value)
values (test_id, val);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.