SQL部分工作但需要一些WHERE子句 - 我想

时间:2013-09-02 11:23:51

标签: mysql

如何更改此SQL以执行以下操作:

  1. 如果用户不在表中,请添加它们。 [本部分工作]
  2. 如果用户在表中并且favourite_active = 0将其更改为favourite_active = 1
  3. 如果用户在表格中并且favourite_active = 1将其更改为favourite_active = 0
  4. 我需要添加WHERE子句。

    $result = mysql_query("SELECT * FROM tbl_favourites WHERE (user_id = '$who' AND favourite_id = '$usernum' AND favourite_active = '1')");
    
    // if user does not exist in favourites, add them
        if(mysql_num_rows($result) == 0) 
        {
             mysql_query("INSERT INTO tbl_favourites (user_id, favourite_id, favourite_active) VALUES ('$who', '$usernum', '1')");
            echo"You have added this user as a favourite";
        } 
    
    // if user does exist and favourite_active = 1 change to 0
        else {
            mysql_query("UPDATE tbl_favourites SET favourite_active='0' WHERE user_id='$who' AND favourite_id='$usernum'"); 
            echo"You have removed this user as a favourite";
        }
    
    // if user does NOT exist and favourite_active = 0 change to 1
        else {
            mysql_query("UPDATE tbl_favourites SET favourite_active='1' WHERE user_id='$who' AND favourite_id='$usernum'"); 
            echo"You have removed this user as a favourite";
        }
    

1 个答案:

答案 0 :(得分:1)

您在IF中不能有两个else子句。并且您无法在两个单独的查询中执行UPDATE,因为第二个查询只会撤消第一个查询。使用以下查询:

UPDATE tbl_favourites SET favourite_active = NOT favourite_active WHERE user_id = '$who' and `favourite_id = '$usernum'

我也不确定你说的第一部分是否有效。您的SELECT查询专门针对favourite_active = 1。如果用户已与favourite_active = 0存在,您将尝试INSERT他们。这真的是你想要的吗?也许你应该删除AND favourite_active = '1'

如果user_idfavourite_id在表格上形成唯一索引,您可以在一个查询中执行整个操作:

INSERT INTO tbl_favourites (user_id, favourite_id, favourite_active)
VALUES ('$who', '$usernum', '1')
ON DUPLICATE KEY UPDATE favourite_active = NOT favourite_active