0

我有一个看起来像这样的插入(使用 MySQL)

INSERT INTO user_actions(action_id,user_id,action_type,record_id,on_table) VALUES
(
    action_id,
    '1',
    '1',
    '32',
    '1'
)
ON DUPLICATE KEY UPDATE 
user_id=user_id AND 
action_type = action_type AND 
record_id = record_id AND 
on_table = on_table

并且action_idAUTO_INCREMENT

仅当某些值不同时才插入表中的目标 si。

我的错误是什么??

其次,我可以用选择做一个 IF、ELSE 吗?喜欢

var_count = count
(
    SELECT action_id FROM user_actions
    WHERE 
    action_id = 'value' AND
    user_id 'value' AND
    action_type 'value'
    record_id 'value' AND
    on_table 'value' AND
)

IF var_count = 0

    INSERT INTO user_actions(action_id,user_id,action_type,record_id,on_table) VALUES
    (
        action_id,
        '1',
        '1',
        '32',
        '1'
    )
    
ELSE

    ... echo error
    
END IF
4

1 回答 1

1

您需要使用,而不是AND

ALTER IGNORE TABLE user_actions ADD UNIQUE KEY ix1(user_id,action_type,record_id,on_table);

这里

INSERT INTO user_actions(action_id,user_id,action_type,record_id,on_table) VALUES
(
 action_id,
 '1',
 '1',
 '32',
 '1'
)
ON DUPLICATE KEY UPDATE 
user_id=user_id,
action_type = action_type,
record_id = record_id,
on_table = on_table;

对于其他SELECT方法,您需要在存储过程中编写这些语句。

CREATE PROCEDURE sp_check_user_actions(arg_action_id INT)
BEGIN
    SELECT count(1)
    INTO @var_count
    FROM user_actions
    WHERE
    action_id = arg_action_id AND
    user_id 'value' AND
    action_type 'value'
    record_id 'value' AND
    on_table 'value';

    IF(@var_count = 0)
    THEN

        INSERT INTO user_actions(action_id,user_id,action_type,record_id,on_table) VALUES
        (
            arg_action_id,
            '1',
            '1',
            '32',
            '1'
        );
    ELSE
        SELECT "Error: Duplicate user action" As error_message;
    END IF;
END;
于 2012-08-02T10:10:04.793 回答