sql - 插入带条件的代码

时间:2015-09-25 09:06:26

标签: php mysql

我正在尝试使用条件编写插入代码 - 如果不存在则插入。我尝试了两种方法,但我收到了错误消息 -

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   'IF NOT EXISTS附近(SELECT * FROM alerts WHERE type ='commentRepl'   在第1行

我做错了什么?

1:

mysql_query("INSERT INTO `alerts` (type, userID, fromID, refID, createDate) VALUES ('commentReply', ".$mainIndex['userID'].", ".$_SESSION['userDetails']['userID'].", ".$refID.", ".get_current_linuxTime().")
        WHERE NOT EXISTS (SELECT * FROM alerts 
                            WHERE type = 'commentReply'
                            AND userID = ".$mainIndex['userID']."
                            AND viewed = 0)
    ");     

2:

mysql_query("
            IF NOT EXISTS (SELECT * 
                            FROM alerts 
                            WHERE type = 'commentReply'
                            AND userID = ".$mainIndex['userID']."
                            AND viewed = 0)
                    BEGIN
                        INSERT INTO `alerts` (type, userID, fromID, refID, createDate) VALUES ('commentReply', ".$mainIndex['userID'].", ".$_SESSION['userDetails']['userID'].", ".$refID.", ".get_current_linuxTime().")
                    END
            ");     

2 个答案:

答案 0 :(得分:1)

除非insert语句为insert into select from

,否则不能将where条件用于select语句

原始mysql语句看起来像

INSERT INTO `alerts` (type, userID, fromID, refID, createDate) 
 select 'commentReply',1,1, 3, curdate()
 from alerts a1
 where not exists(
   select 1 from alerts a2
   where a2.type = 'commentReply'
   and a2.userID = 1
   and a2.viewed = 0
 )

因为你在PHP上使用它所以你可以使用一些你想要的变量

mysql_query(
 "INSERT INTO `alerts` (type, userID, fromID, refID, createDate) 
 select 'commentReply',".$mainIndex['userID'].",".$_SESSION['userDetails']['userID'].", ".$refID.", ".get_current_linuxTime()."
 from alerts a1
 where not exists(
   select 1 from alerts a2
   where a2.type = 'commentReply'
   and a2.userID = ".$mainIndex['userID']."
   and a2.viewed = 0
 )
");

答案 1 :(得分:0)

像这样使用。我希望这会有任何想法:

$exists = "SELECT email, password FROM agent_register WHERE email='$_POST[email]'";
        $exists_result = mysql_query($exists);
        if (mysql_num_rows($exists_result) > 0) {

            $danger_msg = "Error: This email already exists. Please try again.";
        } else {

            if (mysql_num_rows($exists_result) == 0) {

                $sql = "INSERT INTO agent_register(name, company_name, vat_no, status)
                VALUES('$name', '$company_name', '$vat_no', '0')";
                $result=mysql_query($sql);
            }
        }