0

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

  1. 如果用户不在表中,请添加它们。[这部分有效]
  2. 如果用户在表中favourite_active = 0并将其更改为favourite_active = 1.
  3. 如果用户在表中favourite_active = 1并将其更改为favourite_active = 0.

我需要添加我认为的 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";
    }
4

1 回答 1

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
于 2013-09-02T11:33:48.137 回答