如何在更新前查看其他表格?

时间:2016-05-20 15:38:33

标签: php mysql sql pdo

我有这两个表:

 // 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
  • 中的activate列进行比较
  • 检查activeNULL。{/ li>。id = post_id

然后(如果有匹配的行)设置1 activeusers列。我怎么能这样做?

$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));

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

3 个答案:

答案 0 :(得分:2)

您可以使用加入

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

答案 1 :(得分: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)

答案 2 :(得分:1)

我确实相信这个会做的伎俩

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