【问题标题】:How can I check an other table before updating?如何在更新之前检查其他表?
【发布时间】:2016-05-20 15:38:33
【问题描述】:

我有这两张表:

 // users
+----+-------+-----------------------+--------+
| id | name  |       email           | active |
+----+-------+-----------------------+--------+
| 1  | peter | peter12@hotmail.com   | NULL   |
| 2  | jack  | most_wanted@gmail.com | NULL   |
| 3  | john  | john_20016@yahoo.com  | NULL   |
+----+-------+-----------------------+--------+

// activate
+----+---------+---------------------+
| id | post_id |   random_string     |
+----+---------+---------------------+
| 1  | 2       | fewklw23523kf       |
+----+---------+---------------------+

我也有这样的网址:

http://example.com/activate.php?str=fewklw23523kf

我正在尝试做的所有事情:

  • GET['str']random_string 表中的random_string 列进行比较
  • 检查active 列中的NULL,其中id = post_id

然后(如果有匹配的行)从users 表中设置1active 列。我该怎么做?


$str = $_GET['str'];

$stm = $db_con->prepare( "UPDATE users SET active = 1
                          WHERE ( SELECT 1 FROM activate WHERE random_string = ? ) t AND
                                ( SELECT 1 FROM users WHERE t.post_id = id AND
                                                            active IS NULL ) ");

$stmt->execute(array($str));

我的查询没有按预期工作。

【问题讨论】:

    标签: php mysql sql pdo


    【解决方案1】:

    你可以使用join

    UPDATE users 
    INNER JOIN activate on activate.post_id = user.id
    SET active = 1        
    WHERE activate.random_string = ? 
    AND user.active IS NULL;
    

    【讨论】:

    • 作为建议,请您告诉我我的算法是否正确? (激活新帐户)
    • 如果我理解正确,您使用随机生成的字符串通过邮寄方式发送给用户,因此当用户单击您发送的链接时,如果未启用,您将获得此值以启用相关用户..逻辑是对的..
    【解决方案2】:

    尝试改变

    ( SELECT 1 FROM users WHERE t.post_id = id AND active IS NULL )
    

    到这里

    ( SELECT 1 FROM users, activate as t WHERE t.post_id = id AND active IS NULL)
    

    【讨论】:

      【解决方案3】:

      我相信这个可以解决问题

      UPDATE users, activate SET active = 1 
      WHERE users.id = post_id and active is null and random_string=? 
      

      【讨论】:

        猜你喜欢
        • 2021-11-28
        • 2020-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-16
        • 1970-01-01
        • 1970-01-01
        • 2021-11-11
        相关资源
        最近更新 更多