简体   繁体   English

如何根据条件插入?

[英]How to INSERT based on a condition?

I have these INSERT query: 我有这些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));

As you see, query above inserts two rows into events table. 如您所见,上面的查询在events表中插入了两行。 Now I need to put a condition on the way of second row. 现在,我需要在第二行的路上加一个条件。 I mean if $condition is true then inserts second rows, else it shouldn't insert second row. 我的意思是,如果$conditiontrue,则插入第二行,否则不应插入第二行。 (first row always should be inserted) . (始终应插入第一行)

Note: $condition always is containing a boolean value. 注意: $condition始终包含布尔值。

Well, how can I put that condition on the way of second row inserting? 好吧,如何在第二行插入的方式上放置该条件?

You could use a insert select statement like this: 您可以使用以下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) ));

Since the $condition is a php variable why not do it in PHP like so: 由于$ condition是一个php变量,为什么不这样在PHP中这样做:

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

Whats wrong with doing it in 2 queries? 在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));

You can build query string and values array before preparing and executing. 您可以在准备和执行之前构建查询字符串和值数组。

$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