如何在MYSQL中使用IF()和ELSE()语句

时间:2016-12-31 10:23:47

标签: mysql

我想在MYSQL中删除数据或UPDATE数据。如果在字符串 IN()中找到列 message_deleted_by ,则查询应删除 WHERE 子句(过滤)为真的行ELSE查询应使用某些数据更新 message_table message_deleted_by ....所有相同的查询

如果可以实现这一点请帮忙。 我尝试过但尝试输出错误。

$token  =   mysqli_real_escape_string($dbc_conn,encode64(getsecreteToken($_POST["token"])));
    $mid    =   mysqli_real_escape_string($dbc_conn,$_POST["mid"]);
    $rid    =   mysqli_real_escape_string($dbc_conn,$_POST["rid"]);
    $sid    =   mysqli_real_escape_string($dbc_conn,$_POST["sid"]);
    $group  =   implode(",",array($rid,$sid));

    $IsLoggIn   = '2';

    $SQL    =   "
                IF(
                SELECT  message_deleted_by AS mdb FROM $message_tatable
                WHERE (
                        m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
                        ) AND 
                        m.token='$token'  AND m.id='$mid'

                ) mdb  IN($group) THEN

                DELETE  m,mf 
                    FROM $message_tatable m 
                        LEFT JOIN $message_files_tb mf  ON 
                        m.token=mf.token 


                        WHERE (
                        m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
                        ) AND 
                        m.token='$token'  AND m.id='$mid';

                ELSE
                    UPDATE $message_tatable SET message_deleted_by='$IsLoggIn'
                    WHERE (
                            m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
                            ) AND 
                            m.token='$token'  AND m.id='$mid';

                END IF;
                    ";

    //QUERY database
    $query  =   mysqli_query($dbc_conn,$SQL);
    die(mysqli_error($dbc_conn));

1 个答案:

答案 0 :(得分:0)

试试这个,

UPDATE $message_tatable m 
 LEFT JOIN $message_files_tb mf
 ON  m.token=mf.token 
 SET  m=NULL,
  mf=NULL
WHERE m OR mf=SELECT message_deleted_by FROM $message_tatable IN($group)
AND  m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
AND  m.token='$token'  AND m.id='$mid'