繁体   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