帮助逻辑


Help with logic

我有很多对象。它们可以分组。当用户将对象"拖动"到组中时,我会将记录插入到我的数据库中

INSERT INTO t1
  (group_id, item_id, project_id, user_id) 
VALUES 
  ($groupID, $itemID, $projectID, $userID)

同一组中可以有多个对象,这些对象可以从一个组移动到另一个组。当我将对象移动到另一个组中时,我不需要创建另一条记录,而只需要更新group_id。


编辑:

我想我毕竟需要做这样的事情:

table structure
t1.id
t1.group_id
t1.item_id
t1.project_id
t1.user_id
if ("SELECT id, group_id FROM t1 
   WHERE item_id = $itemID
   AND project_id = $projectID
   AND user_id = $userID")) {
   // if found 
   UPDATE t1 
   SET group_id = $groupID
   WHERE id = $ID
} else {
   INSERT INTO t1
   (group_id, item_id, project_id, user_id) 
   VALUES ($groupID, $itemID, $projectID, $userID)

听起来 u 应该在从一个组移动到另一个组时放置一个 if 语句,以仅更新正在移动的对象。例如,如果我从其初始(开始)空间中选择一个对象,我会添加插入语句。如果我正在将已经分组的对象移动到另一个组,我会添加一个更新语句。最后,如果我从所有组中完全取出一个项目,我会发出一个 delete 语句,该语句将从表中删除该对象。

pseudo code
if object = new
{
INSERT INTO t1 (group_id, item_id, project_id, user_id) 
VALUES ($groupID, $itemID, $projectID, $userID)
}
if object = group
}
UPDATE t1 
SET group_id = $newgroupID
WHERE item_id = $itemID;
}
if object = banned
}
delete from t1 where item_id = $itemID
}

此代码序列应放置在要将对象拖动到的每个容器上,以便它可以检查适当的要求。

您可以使用插入在一个查询中执行此操作...在重复密钥更新时。

有关详细信息,请参阅 http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html。

假设item_id是一个键,你可以做

INSERT INTO t1
  (group_id, item_id, project_id, user_id) 
VALUES 
  ($groupID, $itemID, $projectID, $userID)
ON DUPLICATE KEY UPDATE group_id = $groupID

我建议您添加一个代理主键,以便您可以唯一地识别每一行。然后,您可以进行如下更新:

UPDATE t1 SET group_id = $newgroupid WHERE id = $objectid;