我有一张这样的表:
// AcceptedAnswer
+----+---------+-------------+-----------+
| id | user_id | question_id | answer_id |
+----+---------+-------------+-----------+
| 1 | 123 | 4335345 | 3342434 |
| 2 | 345 | 4565546 | 3443565 |
+----+---------+-------------+-----------+
// user_id : the id of that person who is author of question
此外,我在这三列上都有唯一 -index-group:(user_id, question_id, answer_id)
。
有三种情况:
user_id
)想要接受asnwer时。我的脚本也适用于前两种情况。但它并不适用于第三种情况。我该如何实现呢?
这是我的剧本:
try {
// DB connection here
// This SELECT statement validates whether user_id is the author of the question
$stmt = $db_con->prepare("INSERT INTO AcceptedAnswer(user_id, question_id, answer_id)
SELECT ?,?,?
FROM questions q
WHERE q.id = ? and q.author_id = ? limit 1;");
$stmt->execute( array( $_SESSION["Id"], $question_id, $answer_id,
$question_id, $_SESSION["Id"] ) );
} catch(PDOException $e) {
// undo acceptance
if ((int) $e->getCode() === 23000) {
$stmt = $dbh_conn->prepare(" DELETE FROM AcceptedAnswer
WHERE user_id = ? AND
question_id = ? AND
answer_id = ? ");
$stmt->execute(array($_SESSION["Id"], $question_id, $answer_id));
}
例如: (基于上表)
当我通过时:(123, 4335345, 2353423)
(更改已接受的答案),预期输出:
// AcceptedAnswer
+----+---------+-------------+-----------+
| id | user_id | question_id | answer_id |
+----+---------+-------------+-----------+
| 1 | 123 | 4335345 | 2353423 |
| 2 | 345 | 4565546 | 3443565 |
+----+---------+-------------+-----------+
当我通过时:(345, 4565546, 3443565)
(撤消已接受的答案),预期输出:
// AcceptedAnswer
+----+---------+-------------+-----------+
| id | user_id | question_id | answer_id |
+----+---------+-------------+-----------+
| 1 | 123 | 4335345 | 2353423 |
+----+---------+-------------+-----------+
答案 0 :(得分:1)
首先,您无法将这两个查询组合在一起,因为它们是互斥的。
此外,您似乎根本不需要REPLACE INTO。
实际上,你只需要两个查询,一个是INSERT,ON DUPLICATE接受任何答案,一个是删除 - 不接受。
此外,我只使用一个简单的条件来查看表单中是接受还是不接受,而不是异常处理。
请注意,if条件indide catch块中应该有一个else子句,如果不是预期的话,重新抛出异常。