本文介绍了如何根据条件插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下这些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
表中插入了两行.现在,我需要在第二行的路上加一个条件.我的意思是,如果$condition
是 true ,则插入第二行,否则不应该插入第二行. (始终应插入第一行).
As you see, query above inserts two rows into events
table. 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. (first row always should be inserted).
注意: $condition
始终包含布尔值.
那么,如何在第二行插入的方式上添加该条件?
Well, how can I put that condition on the way of second row inserting?
推荐答案
您可以使用insert select
语句,如下所示:
You could use a insert select
statement like this:
$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) ));
这篇关于如何根据条件插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!