0

There is a way that MySQL to check record which is going to INSERT is duplicate or not is using:

INSERT ... ON DUPLICATE KEY UPDATE 

But as the document says: the KEY to check is the primary key.And in my situation,I need to check tow fields (columns) to make sure it is duplicate or not.My table structure:

auto_id  user_id  file_id file_status
1        1        12        1
2        3        12        0
3        1        17        1
4        4        31        1
5        1        41        0
6        4        31        0
7        1        18        1
8        5        11        0
9        1        10        0

E.g:Maybe like:

ON DUPLICATE user_id,file_id UPDATE file_status = 0;

if user_id and file_id which in one record were duplicate,I will update the file_status to 0.

Thank you very much!!

[update]

So,I have to do it in several steps!?

First, find out the records exist or not:

SELECT auto_id FROM MyTable WHERE user_id='user_id' AND file_id='file_id'.

Second, decide to INSERT new record or UPDATE according to the SELECT result!

3 Answers 3

2

You can also create a stored procedure and check if the file_id already exists or not:

drop if procedure exists check_user_files;
create procedure check_user_files
(
    in p_file_id smallint
)
begin
    declare v_success tinyint unsigned default 0;

    if not exists (select 1 from user_files where file_id = p_file_id) then

        [....] -- insert statement

    else

        [....] -- remove or update

    end if;

    select v_success as success;
end;

And where are u using auto_id for? I think its unnecessary here?

Sign up to request clarification or add additional context in comments.

2 Comments

How can I call the store procedure at multi-times to check all records!
you can do it by call check_user_files(file_id) its just like a php function but then only with call before it
0

I believe that the duplicate check is for the violation of any unique index as well as the primary key. At least according to the manual page.

Comments

0

A suggestion, if you have you're main id (auto_id) on auto increment then why not make those 2 columns your primary key so if you try to enter a value that matches it will through an error

1 Comment

With your suggestion,because the auto_id is different,so MySQL will not through an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.