我有2个表:具有列(id,用户名,密码)的user和带有列的user_failed(user_id,failed,time)。是否有任何可能的方法我只能使用用户名插入表user_failed?我尝试这个代码,但它失败了:
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (SELECT user_id FROM users WHERE username = 'pokemon','',3)
答案 0 :(得分:3)
由于多种原因,您的SQL查询不正确。
如果我已正确解释您的查询,以下内容应该有效。
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
SELECT id, '', 3 FROM users WHERE username = 'pokemon'
INSERT
来自SELECT
的表格不需要VALUES ( ... )
。以下是如何使用VALUES ( ... )
:
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (1, '', 3)
此外,您的子查询SELECT user_id FROM users WHERE username = 'pokemon','',3
WHERE
子句无效。具体而言,我假设的'',3
部分是您要为time
和failed
插入的值。
答案 1 :(得分:1)
这将起作用....你必须在语句之前和之后添加普通括号。
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`) VALUES ((SELECT user_id FROM users WHERE username = 'pokemon'),'',3)