0

假设我们有一个类似这样的 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 在 db 中存在,则应该更新。)

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

2 回答 2

1

有单独的查询是一种非常普遍的做法,它没有任何问题。但是,至少 mySQL 提供了一个replace into命令:

REPLACE INTO availability
    (userid, days, opentime, closetime) VALUES
    (?,    'Monday', ?,         ?);

唯一的缺点是,您不能指定 where 子句。

另请参阅https://stackoverflow.com/a/3046980/1596455

于 2013-09-06T06:38:29.747 回答
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) ;
     "; 
于 2013-09-06T06:44:28.027 回答