如何比较mysql存储过程中的两个列值

时间:2016-04-09 08:35:50

标签: mysql

我正在尝试使用连接获取两列,以下查询工作正常,现在我如何使用if语句比较这两个值。

SELECT 
    failed = L.failed_attempts AS 'FAILED ATTEMPTS',
    s_value = s.setting_value as 'SETTING VALUE'
FROM login_t L
INNER JOIN settings_t S ON S.SETTING_NAME = 'login_attempts'
WHERE L.login_id = id  
  AND L.failed_attempts > S.setting_value;

如果failed_attempts > settings_value,则将is_logged_in中的login_t列值更新为0并返回false,否则返回true

PS:我正在使用mysql存储过程

1 个答案:

答案 0 :(得分:0)

如果你的select语句总是只返回一行,你可以存储选定的值INTO局部变量,你应该先DECALRE。然后,您可以使用IF .. THEN .. ELSE .. END IF;:返回您需要的内容SELECT someValue。 我不是应该比得上的。但这就是方法,你可以这样做:

DECLARE FAILED_ATTEMPTS INT;
DECLARE SETTING_VALUE   INT;

SELECT 
    failed = L.failed_attempts,
    s_value = s.setting_value
INTO 
    FAILED_ATTEMPTS,
    SETTING_VALUE
FROM login_t L
INNER JOIN settings_t S ON S.SETTING_NAME = 'login_attempts'
WHERE L.login_id = id  
  AND L.failed_attempts > S.setting_value;

IF FAILED_ATTEMPTS > SETTING_VALUE
THEN
    -- your update statement here
    SELECT FALSE;
ELSE
    SELECT TRUE;
END IF;

也许你需要

SELECT 
    L.failed_attempts,
    s.setting_value
INTO 
    FAILED_ATTEMPTS,
    SETTING_VALUE

但不知怎的,我想你需要两个选择语句:

SELECT L.failed_attempts,
INTO FAILED_ATTEMPTS
FROM login_t L
WHERE L.login_id = id;

SELECT s.setting_value
INTO SETTING_VALUE
FROM settings_t S
WHERE S.SETTING_NAME = 'login_attempts';