带插入和更新的MySQL程序

时间:2017-06-05 02:07:08

标签: mysql

我需要一些帮助来在MySQL中创建一个过程。

我有两张桌子:

  1. 连接
  2. connection_temporary
  3. 我想创建一个程序:

    • 如果// GET: api/Posts public IHttpActionResult Get() { PostsStore store = new PostsStore(); var AsyncResult = store.GetPosts(); return Ok(AsyncResult); } // GET: api/Posts/5 public IHttpActionResult Get(string slug) { PostsStore store = new PostsStore(); var AsyncResult = store.GetBySlug(slug); return Ok(AsyncResult); } // POST: api/Posts public IHttpActionResult Post(Post post) { PostsStore store = new PostsStore(); ResponseResult AsyncResult = store.Create(post); return Ok(AsyncResult); } // PUT: api/Posts/5 DELETED to make sure I wasn't hitting some sort of precedent issue. //public IHttpActionResult Put(Post post) // { // return Ok(); //} [HttpPut] [Route("save")] public IHttpActionResult Save(Post post) { PostsStore store = new PostsStore(); ResponseResult AsyncResponse = store.Save(post); return Ok(AsyncResponse); } 将connection.connection_status更新为离线
    • 如果SELECT keyname FROM connection WHERE keyname NOT IN (SELECT keyname FROM connection_temporary) 与connection_temporary的行内容一起插入
    • 如果SELECT keyname FROM connection_temporary WHERE keyname NOT IN (SELECT keyname FROM CONNECTION) 使用connection_temporary的行内容更新连接

    我该怎么做?

1 个答案:

答案 0 :(得分:0)

您应该发布两个表的架构,但您可以根据以下内容自行尝试:

DELIMITER $$
CREATE PROCEDURE `proc`()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
    UPDATE `connection`
    SET `connection`.connection_status = 'offline'
    WHERE NOT EXISTS(
        SELECT 1 
        FROM connection_temporary
        WHERE connection_temporary.keyname = `connection`.keyname
    );

    INSERT INTO `connection` (keyname, real_ip, virtual_ip, received_bytes, sent_bytes, connection_tstamp)
    SELECT keyname, real_ip, virtual_ip, received_bytes, sent_bytes, connection_tstamp
    FROM connection_temporary
    WHERE NOT EXISTS(
        SELECT 1
        FROM `connection`
        WHERE connection_temporary.keyname = `connection`.keyname
    );

    UPDATE `connection`
    JOIN connection_temporary ON connection_temporary.keyname = `connection`.keyname
    SET `connection`.keyname = connection_temporary.keyname
    ,`connection`.real_ip = connection_temporary.real_ip
    ,`connection`.virtual_ip = connection_temporary.virtual_ip
    ,`connection`.received_bytes = connection_temporary.received_bytes
    ,`connection`.sent_bytes = connection_temporary.sent_bytes
    ,`connection`.connection_tstamp = connection_temporary.connection_tstamp; 
END
$$ DELIMITER ;