简体   繁体   English

如果行不存在则插入否则更新行

[英]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.如果用户已经投反对票并且插入了一条记录,这次他想更改为投赞成票:我只想更新记录并将投票状态设置为 1,同样如果用户请求投反对票并且记录是由同一用户插入,然后只需更新记录并将列状态设置为 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;我写了一个 SQL 来完成这项工作,但它在网络控制台下给了我错误:你的 SQL 语法有错误; 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检查与您的 MariaDB 服务器版本相对应的手册,以在第 8 行的 'UPDATE votes VT SET VT.vote_status = '1', VT.vote_time='1583319756' ' 附近使用正确的语法

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.我不想使用 sql ON DUPLICATE 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.我想检查 2 或 3 列是否与我要插入的记录相同,然后更新其他插入。

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 "您可以使用“合并到”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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