如何基于其他一个插入表?

时间:2016-05-20 18:14:06

标签: mysql sql join insert

我有这两个表:

 // 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       |
+----+---------+---------------------+

我也有这两个变量:

$random string = 'gergflkw4534l';
$email = 'peter12@hotmail.com';

我想基于这两个变量在activate表中插入一个新行。这是预期的结果:

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

如您所见,我根据post_id列从users表中获取email。我怎么能这样做?

INSERT INTO activate VALUES (null, /* I don't know */, :random_string)
INNER JOIN users ON /* I don't know */
WHERE email = :email

2 个答案:

答案 0 :(得分:1)

你的语法非常不合适。在实际WHERE任何内容之前,您需要一个JOIN子句。我将假设Activate表中的id列是自动编号列。

INSERT INTO Activate (post_id, random_string)
SELECT
    id,
    :random_string
FROM
    Users
WHERE
    email = :email

答案 1 :(得分:1)

您可能希望使用mysql insert-select语法:

INSERT INTO activate (post_id, random_string)
SELECT id, :random_string
FROM users 
WHERE email = :email
LIMIT 1;