简体   繁体   中英

insert if row do not exists else update row

I have auto incremented field in votes table where user can up-vote and down-vote on a post. If a user request to up-vote on the post, I want to check the table to see if they have already voted(down or up).

if the user already down-vote and a record is inserted and this time he wants to change to up-vote: I just want to update the record and set vote status to 1, likewise If user request to down-vote and a record is inserted by the same user then just update record and set column status to 0.

I wrote an SQL to do this job but it gives me error under network console : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE votes VT SET VT.vote_status = '1', VT.vote_time='1583319756' ' at line 8

I have search couple of examples but it doesn't see to work. I do not want to use sql ON DUPLICATE KEY I have read it only for the duplicate unique key.

I want to check if 2 or 3 columns is the same as the record I want to insert exist, then update else insert.

How do I achieve this?

my code:

IF EXISTS (
                SELECT * FROM $votes_table VT WHERE VT.vote_ask_id='{$Qid}' 
                AND VT.vote_type='{$vote_type}' 
                AND VT.vote_status='{$vote_down_status}'
                AND VT.vote_user_id='{$CUid}'

                ) 
    UPDATE  $votes_table VT SET 
            VT.vote_status = '{$vote_up_status}',
            VT.vote_time='{$current_time}' 
            WHERE VT.vote_user_id = '{$CUid}' 
            AND VT.vote_ask_id = '{$Qid}' 

    ELSE    INSERT INTO $votes_table(vote_ask_id,vote_type,vote_status,vote_user_id,vote_time) 
            VALUES('{$Qid}','{$vote_type}','{$vote_up_status}','{$CUid}','{$current_time}')

I recommend you change function update and insert. You can use "Merge into "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM