gpt4 book ai didi

php - 如何对插入和更新进行单个查询?

转载 作者:行者123 更新时间:2023-11-29 08:23:28 25 4
gpt4 key购买 nike

假设我们有一个类似这样的 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,

使用这些数据,我需要更新或插入我的表。 (如果表中不存在用户 ID,则应插入该用户 ID;如果数据库中存在用户 ID,则应更新该用户 ID。)

我可以知道,有没有办法为此进行 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);

最佳答案

如果您在(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) ;
     "; 

关于php - 如何对插入和更新进行单个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com