2
我有兩個疑問:如何根據條件將一些項目添加到數組中?
$db
->prepare("UPDATE users
SET reputation = reputation + (CASE id WHEN ? THEN 2 WHEN ? THEN 15 END),
Money = Money + (CASE id WHEN ? THEN ? WHEN ? THEN ? END)
WHERE id IN (?, ?); ")
->execute(array($author_ques_id, $author_ans_id,
$author_ques_id, $asker_amount, $author_ans_id, $responder_amount,
$author_ans_id, $author_ques_id));
$db
->prepare("INSERT INTO events (type, score, post_id, table_code, user_id, author_id, date_time)
VALUES (4 , 2 , ? , 15 , ? , ? , UNIX_TIMESTAMP()),
(4 , 15 , ? , 15 , ? , ? , UNIX_TIMESTAMP()),
(5 , ? , ? , 15 , ? , ? , UNIX_TIMESTAMP()),
(5 , ? , ? , 15 , ? , ? , UNIX_TIMESTAMP())")
->execute(array($answer_id, $author_ques_id, $author_ques_id,
$answer_id, $author_ques_id, $author_ans_id,
$asker_amount, $ques_id, $author_ques_id, $author_ques_id,
$responder_amount, $answer_id, $author_ques_id, $author_ans_id));
這兩個以上的查詢應該是正確的,當這個條件爲真:
if ($author_ques_id != $author_ans_id) {
// then queries above are fine
} else {
// queries should be like below
}
正如我評論中的條件之上,如果這一條件是假 ,那麼這兩個查詢應該是這樣的:
$db
->prepare("UPDATE users
SET reputation = reputation + 2,
Money = Money + ?
WHERE id ?; ")
->execute(array($asker_amount,
$author_ques_id));
$db
->prepare("INSERT INTO events (type, score, post_id, table_code, user_id, author_id, date_time)
VALUES (4 , 2 , ? , 15 , ? , ? , UNIX_TIMESTAMP()),
(5 , ? , ? , 15 , ? , ? , UNIX_TIMESTAMP())")
->execute(array($answer_id, $author_ques_id, $author_ques_id,
$asker_amount, $ques_id, $author_ques_id, $author_ques_id));
好的,我只想知道,sh我應該爲每個案例寫兩次這些查詢嗎?或者我可以根據這種情況創建一個動態查詢?
這是匆忙變得凌亂。你確定沒有辦法做到這一點,而不依靠'CASE'聲明這麼重要?在一個事務內部的一系列簡單的'UPDATE'語句通常比這樣一個複雜的SQL塊更好。 – tadman