开发者

How to check if tow columns are duplicate when INSERT data in MySQL?

开发者 https://www.devze.com 2023-02-20 05:41 出处:网络
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

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 开发者_如何学Gofile_id='file_id'.

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


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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消