在单个查询中更新和插入


Update and Insert in a Single Query

我有一个包含pageiddepartmentpositionactive的表。在更新时,如果pageid已经存在,我必须更新active列,否则我将插入一个带有pageid的新行。

我通过复选框获取页面ID值,我的更新查询如下

$sql = "INSERT INTO access_level (page_id, department, position, active) 
               VALUES (".$sn.", ".$department.", ".$position.", 1) 
        ON DUPLICATE KEY UPDATE
        department=VALUES(".$department."), 
        position=VALUES(".$position."), 
        active=VALUES(1)";

但在这种情况下,所有内容都被插入了两次。

我哪里做错了?有人能指引我吗?

这可能对您有用:

$sql = "INSERT INTO access_level (page_id, department, position, active) 
               VALUES (".$sn.", ".$department.", ".$position.", 1) 
        ON DUPLICATE KEY UPDATE
        id=LAST_INSERT_ID(id),  
        active=VALUES(1)";