否則更新在這樣的表:MySQL表插入,如果不存在非唯一列
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
}
做,但不是還有一個班輪?
我看着Insert into a MySQL table or update if exists和MySQL procedure to create or update a row in a table和MySql Insert if not exist two column pair otherwise update,但那些不適用,除非我的'user_ID'和'name'列是唯一的,是嗎?
見INSERT ... ON DUPLICATE KEY - 和規範化讀了太多 – Strawberry
檢查這個https://dev.mysql.com/doc/refman/ 5.7/en/insert-on-duplicate.html –
@Strawberry我誤以爲INSERT ... ON DUPLICATE KEY只有在列中有唯一值時才起作用?規範化意味着什麼? – Konservin