簡體   English   中英

如何根據條件插入?

[英]How to INSERT based on a condition?

我有這些INSERT查詢:

$db->prepare("INSERT INTO
              events (post_id, table_code, other_id, user_id, author_id, date_time )
              VALUES (?      , 15        , ?       , ?      , ?        , UNIX_TIMESTAMP()),
                     (?      , 15        , ?       , ?      , ?        , UNIX_TIMESTAMP())
")->execute(array($answer_id, $answer_id, $author_ques_id, $author_ques_id,
                  $answer_id, $answer_id, $author_ques_id, $author_ans_id));

如您所見,上面的查詢在events表中插入了兩行。 現在,我需要在第二行的路上加一個條件。 我的意思是,如果$conditiontrue,則插入第二行,否則不應插入第二行。 (始終應插入第一行)

注意: $condition始終包含布爾值。

好吧,如何在第二行插入的方式上放置該條件?

您可以使用以下insert select語句:

$db
->prepare("INSERT INTO
             events (post_id, table_code, other_id, user_id, author_id, date_time )
             select ?, 15, ?, ?, ?, UNIX_TIMESTAMP()
              UNION ALL
             select ?, 15, ?, ?, ?, UNIX_TIMESTAMP()
               from (select 1) as a
              where 1=?
")->execute(array($answer_id, $answer_id, $author_ques_id, $author_ques_id,
                  $answer_id, $answer_id, $author_ques_id, $author_ans_id,
                  ($yourCondition?1:0) ));

由於$ condition是一個php變量,為什么不這樣在PHP中這樣做:

if ($condition === true) {
    $db->prepare($first_and_seccond_row);
} else {
    $db->prepare($first_row);
}

在2個查詢中這樣做有什么問題?

$query = $db->prepare("INSERT INTO
              events (post_id, table_code, other_id, user_id, author_id, date_time)
              VALUES (?, 15, ?, ?, ?, UNIX_TIMESTAMP())");

$query->execute(array($answer_id1, $answer_id1, $author_ques_id1, $author_ans_id1));

if ($condition)
    $query->execute(array($answer_id2, $answer_id2, $author_ques_id2, $author_ans_id2));

您可以在准備和執行之前構建查詢字符串和值數組。

$query = "INSERT INTO
          events (post_id, table_code, other_id, user_id, author_id, date_time )
          VALUES (?, 15, ?, ?, ?, UNIX_TIMESTAMP())";
$values = array($answer_id, $answer_id, $author_ques_id, $author_ques_id);
if ($condition) {
    $query .= ",(?, 15, ?, ?, ?, UNIX_TIMESTAMP())";
    $values = array_merge($values, array($answer_id, $answer_id, $author_ques_id, $author_ans_id);
}
$db->prepare($query)->execute($values);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM