mysql - MySql 中的内存表和临时表

标签 mysql sql-server database tsql stored-procedures

我正在寻找 MySql 中的 Sql-Server 相关功能

过程内的表变量。 here

程序内的临时表。 here

我希望表变量位于内存中,临时表存储在临时数据库中。 如果两者都在过程内部声明,则在过程执行完成后两者都会被清除。

MySql 只提供一种称为临时表的选项。如何实现这两个呢?我们是否需要清除这些表,或者 MySql 会在程序完成后处理它?<​​/p>

最佳答案

来自 MySQL 文档:

You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. More info: http://dev.mysql.com/doc/refman/5.1/en/create-table.html#create-temporary-table

但是如果我使用单个连接会发生什么?可能您会遇到一些数据冲突。过去,如果我多次调用具有相同连接的过程,我会使用具有唯一 id 的临时表来避免冲突:

DELIMITER $$
DROP PROCEDURE some_proc $$
CREATE PROCEDURE some_proc () 
BEGIN

    -- creating a unique value
    DECLARE VARIABLE tmp_uuid varchar(50);
    SET tmp_uuid = uuid();


    CREATE TEMPORARY TABLE IF NOT EXISTS tbl_temporary
    (
        uuid_id varchar(50), 
        col1 varchar(10),
        col2 varchar(10),
        INDEX(uuid_id)
    );

   -- do some operations on that

    INSERT INTO tbl_temporary(uuid_id, ...) VALUES (tmp_uuid,...);


    -- now, cleaning the data
    DELETE FROM tbl_temporary WHERE uuid_id = tmp_uuid;

    -- if the current session is closed the table will be automatically deleted
END$$

DELIMITER ;

关于mysql - MySql 中的内存表和临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27242892/

相关文章:

php mysqli 使用通配符准备语句

mysql - SQL 和 VBScript : How to store an SQL query column (USER_FIRSTNAME) into a VBScript variable?

mysql - 在 MySQL 中创建表时,我无法克服语法错误 有人会发现错误吗?

sql-server - SQL Server : What are batching statements (i.使用 "GO")有什么好处?

mysql - 如何在 MYSQL 中更改用户的 GRANTS?

sql-server - 一台服务器上两个数据库的查询性能

php - 在创建新行条目时从 mysql 行中检索时间戳

sql - 如何根据第一个查询运行第二个查询?

sql - 如何使用 Print 语句打印 VARCHAR(MAX)?

PHP Laravel eloquent with multiple databases,其实是select something