简体   繁体   English

如果存在,则为UPDATE Table,否则在Table中插入新行

[英]If exists, UPDATE Table , Else Insert New Row In Table

I have the following line of query in my stored procedure. 我的存储过程中有以下查询行。 The purpose of this stored procedure is if the website link is already in the table, it will update the existing one. 此存储过程的目的是,如果网站链接已在表中,它将更新现有链接。 If not it will record as new row from the other table' value. 如果不是,它将记录为另一个表的值的新行。

CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_diffmod_v2`( 
IN para_diffmod LONGTEXT, 
IN para_link LONGTEXT)
BEGIN

IF EXISTS (
    SELECT website_link FROM diffmod WHERE website_link=para_link
    )THEN 
    UPDATE diffmod
    SET diffmod_content=para_diffmod
    WHERE website_link= para_link; 

ELSE
    INSERT INTO diffmod(website_id,website_link)
    SELECT id,link
    FROM   site_html
    Where  link=para_link;

    UPDATE diffmod
    SET diffmod_content= para_diffmod
    where website_link = para_link;

END IF; 
END

Let's say www.google.com is already recorded. 假设www.google.com已被记录。 When I call like: 当我打电话给:

CALL myDB.insert_diffmod_v2('test','www.google.com'); 

there is no problem and it do update the existing record. 没问题,它会更新现有记录。

But when I called the link which is not in the record (let's say Yahoo) like 但是当我调用不在记录中的链接时(例如Yahoo),

CALL  myDB.insert_diffmod_v2('test','www.yahoo.com');

it didn't insert as new record in the table. 它没有作为新记录插入表中。 Can I know why ? 我能知道为什么吗?

Insert in to on duplicate key update example 插入重复密钥更新示例

"$" are parameters and make website_id,website_link as unique “ $”是参数,并使website_id,website_link唯一

INSERT INTO diffmod SET
        website_id = (SELECT id FROM   site_html Where  link=@para_link),
        website_link= $para_link,
        diffmod_content=$para_diffmod
        ON DUPLICATE KEY UPDATE
        diffmod_content=$para_diffmod

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

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