加入两个表,然后搜索匹配

时间:2013-07-01 09:42:47

标签: mysql

我有两个名为security_questions和login的表。登录表中的列是:

Username, Security_QA_ID, Security_Answer, Security_Attempts,Last_Login,Password_Attempts

security_questions有:

ID, Name

其中Security_QA_ID以ID

引用
CREATE DEFINER=`satish`@`%` PROCEDURE `p_chkAnswer`(
IN sq VARCHAR(75),
IN sa VARCHAR(20) ,
IN uname VARCHAR(15) ,
out msg INT
)
BEGIN
select (COUNT(*) > 0) INTO @result from login join security_questions on Security_QA_ID = ID where User_Name=uname and Name=sq and Security_Answer=sa;
set msg = @result;
if @result = 1 Then
UPDATE login SET  Last_Login=now(),Password_Attempts=0 where User_Name=uname;
else
UPDATE login SET  Security_Attempts=Security_Attempts+1 where User_Name=uname;
End if;

END 

但每次只有部分得到执行。提前谢谢

1 个答案:

答案 0 :(得分:0)

您的代码非常混乱且难以阅读(至少对我而言),我将您的语句简化为单个SELECT,以便我可以检查您的选择是否正确,并且看起来是正确的:

CREATE TABLE `login`
 ( User_Name text, 
   Security_QA_ID int(11),
   Security_Answer text,
   Security_Attempts datetime,
   Last_Login datetime,
   Password_Attempts int(11)
 );

CREATE TABLE `security_questions`
 (ID int(11), 
  Name text
  );

INSERT INTO login SET
 User_name = 'a',
 Security_QA_ID = 1,
 Security_Answer = 'c',
 Security_Attempts = NOW(),
 Last_Login = NOW(),
 Password_Attempts = 0;

INSERT INTO security_questions SET
 ID = 1,
 Name = 'b';

选择

SELECT IF(COUNT(*) > 0, 1, 0) AS Authenticated
from (login)
LEFT join security_questions on Security_QA_ID = ID 
where User_Name='a' and Name='b' and Security_Answer='c'

你必须使用这个 DEFINER 吗?编写PHP / Perl / etc代码来检查 Authenticated 是非零会不会更容易?