我有一个简单的表,逻辑是在插入新行之前,我应该从该表中获取一列。让我解释一下:
table
id key groupId Note
1 00001 1 abd
2 00002 1 aasdas
3 00003 1 aasdas
4 00001 2 q2eqwd
5 00002 2 qwdvvd
6 00003 2 qwrqw
7 00004 2 qwdqdqw
您会看到,每个groupId的自动增量键增加。 当id为2的组想要添加新音符时,他应该知道最后一个键。找到它之后,php将+1添加到最后一个键并插入一个新行。我这样做如下:
$groupId = 2; //for example
$note = $_POST['note'];
$select = $db -> prepare("SELECT key FROM table where groupId = :groupId ORDER BY id DESC limit 1");
$select -> bindValue(":groupId", $groupId, PDO::PARAM_INT);
$select -> execute();
$fetch = $select -> fetch(PDO::FETCH_ASSOC);
$lastKey = $fetch['key']+1;
$insert = "INSERT INTO table (key, groupId, note) VALUES(:key, :groupId, :note)";
$ins = $db -> prepare($insert);
$insert -> bindValue(":key", $lastKey, PDO::PARAM_INT);
$insert -> bindValue(":groupId", $groupId, PDO::PARAM_INT);
$insert -> bindValue(":note", $note, PDO::PARAM_STR);
这种方法对我有用,但我担心在从表中获取最后一个键时会出现任何冲突吗?因为,同时,具有相同groupId的10个用户可以添加新行。 php可以同时为3个用户组ID ID 2获取相同的密钥吗?
有没有快速安全的方式?
答案 0 :(得分:1)
您可以使用MyISAM AUTO_INCREMENT
执行此操作。
来自MySQL Docs:
对于MyISAM和BDB表,您可以在a上指定AUTO_INCREMENT 多列索引中的辅助列。 ...当您想要将数据放入有序组时,这非常有用。
否则,您应该使用类似SELECT MAX(key) + 1 FROM table WHERE groupID = 1
的子查询设置插入查询中的值,并回读该值。