0

因此,当我在插入数据时有重复值时出现此错误,现在我的查询是正确的,我尝试在 phpmyadmin 中运行它,并且工作正常,但是 kohana 给了我错误,这就是我的查询的样子:

DB::query(Database::INSERT, 'INSERT INTO `views` ( user_id, viewer_id, username, picture, view_time, view_count) 
                    VALUES ("'.$this->request->param('id2').'", "'.$user->id.'", "'.$user->username.'", "'.$user->picture.'", '.DB::expr('NOW()').', "1")
                    ON DUPLICATE KEY UPDATE `view_time` = NOW(), `view_count` = view_count +1

在纯 sql 中:

INSERT INTO `views` ( user_id, viewer_id, username, picture, view_time, view_count )
VALUES (
"134173", "139173", "username", "pic.jpg", NOW( ) , "1"
) ON DUPLICATE
KEY UPDATE `view_time` = NOW( ) ,
`view_count` = view_count +1

所以基本上我尝试插入并更新我更新的重复值,但由于某种原因,kohana 给了我错误:

kohana Database_Exception [ 1062 ]: Duplicate entry

我怎样才能消除这个错误?

4

1 回答 1

2

也许通过不指定查询类型来尝试这种方法:

$query = " 
  INSERT INTO `views` (user_id, viewer_id, username, picture, view_time, view_count)
  VALUES (%d, %d, '%s', '%s', %s, %d)
  ON DUPLICATE KEY UPDATE `view_time` = %s, `view_count` = view_count + 1";

$query = sprintf($query, $this->request->param('id2'), $user->id, $user->username, $user->picture, DB::expr('NOW()'), 1, DB::expr('NOW()'));

$result = Database::instance()->query(NULL, $query);
于 2012-02-04T17:53:07.697 回答