假设我们有一个类似这样的mysql表
id, userid, days, start, and close
我们有像这样的每一列的数据 -
1, 3, mon, 01.00, 02.00,
2, 3, tue, 03.00, 05.00,
3, 3, wed, 04.00, 06.00,
4, 3, thu, 05.00, 07.00,
5, 3, fri, 06.00, 08.00,
6, 3, sat, 07.00, 10.00,
7, 3, sun, 08.00, 12.00,
有了这些数据,我需要更新或插入我的表格。 (如果表中不存在userid,则应插入,如果db中存在userid,则应更新。)
我可以知道,有没有办法为此进行mysql单一查询?我用INSERT ... ON DUPLICATE KEY UPDATE
尝试了它,我只能编辑单行,这意味着我无法使用INSERT ... ON DUPLICATE KEY UPDATE
插入或更新包含多行的表。
目前我已使用2个不同的查询进行插入和更新
这是我的插入查询 -
$q = "INSERT INTO availability (userid, days, opentime, closetime)
VALUES (?, 'Monday', ?, ?),
(?, 'Tuesday', ?, ?),
(?, 'Wednesday', ?, ?),
(?, 'Thursday', ?, ?),
(?, 'Friday', ?, ?),
(?, 'Saturday', ?, ?),
(?, 'Sunday', ?, ?)";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'issississississississ',
$userId, $monOpen, $monClose,
$userId, $tueOpen, $tueClose,
$userId, $wedOpen, $wedClose,
$userId, $thuOpen, $thuClose,
$userId, $friOpen, $friClose,
$userId, $satOpen, $satClose,
$userId, $sunOpen, $sunClose);
// Execute the query:
mysqli_stmt_execute($stmt);
答案 0 :(得分:1)
单独查询是一种非常常见的做法,它没有任何问题。但是,至少mySQL提供了replace into
命令:
REPLACE INTO availability
(userid, days, opentime, closetime) VALUES
(?, 'Monday', ?, ?);
唯一的缺点是,你不能指定where子句。
答案 1 :(得分:1)
如果您在(userid, days)
上添加唯一索引:
-- run this only once
ALTER TABLE availability
ADD UNIQUE INDEX userid_days_UQ -- just a name for the index
(userid, days) ;
然后您可以使用ON DUPLICATE KEY UPDATE
语法:
$q = "
INSERT INTO availability
(userid, days, opentime, closetime)
VALUES
(?, 'Monday', ?, ?),
(?, 'Tuesday', ?, ?),
(?, 'Wednesday', ?, ?),
(?, 'Thursday', ?, ?),
(?, 'Friday', ?, ?),
(?, 'Saturday', ?, ?),
(?, 'Sunday', ?, ?)
ON DUPLICATE KEY UPDATE
opentime = VALUES(opentime),
closetime = VALUES(closetime) ;
";