我有这两个表:
// 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
答案 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;