INSERT INTO不重复特定列的位置

时间:2012-08-02 10:07:51

标签: mysql sql sql-server phpmyadmin mysqli

我有一个看起来像这样的插件(使用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

...

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要使用,代替AND

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

请参阅here

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;