子查询中的mysql临时表

时间:2018-02-23 19:37:49

标签: mysql stored-procedures subquery temp-tables

我正在尝试在子查询(存储过程)中使用临时表,但它返回空结果集...

CREATE DEFINER=`root`@`localhost` PROCEDURE `get_profile_with_templates`(IN _username NVARCHAR(50), IN _template NVARCHAR(50))
BEGIN
    SELECT id INTO @template FROM profile_template WHERE name=_template LIMIT 1;
    SELECT * FROM profile WHERE username=_username AND template=@template LIMIT 1;
    CREATE TEMPORARY TABLE IF NOT EXISTS sections SELECT * FROM profile_template_section WHERE template=@template;
    **CREATE TEMPORARY TABLE IF NOT EXISTS components SELECT * FROM component_template WHERE section IN (SELECT id FROM sections);**
    SELECT * FROM sections;
    SELECT * FROM components;
    SELECT * FROM component_template_option WHERE component_template IN (SELECT id FROM components);
END

**之间的查询是一个返回空的... 如果我在真实表上运行相同的查询,它返回值...

CREATE DEFINER=`root`@`localhost` PROCEDURE `get_profile_with_templates`(IN _username NVARCHAR(50), IN _template NVARCHAR(50))
BEGIN
    DROP TEMPORARY TABLE IF EXISTS sections;
    DROP TEMPORARY TABLE IF EXISTS components;
    SELECT id INTO @template FROM profile_template WHERE name=_template LIMIT 1;
    SELECT * FROM profile WHERE username=_username AND template=@template LIMIT 1;
    CREATE TEMPORARY TABLE IF NOT EXISTS sections SELECT * FROM profile_template_section WHERE template=@template;
    CREATE TEMPORARY TABLE IF NOT EXISTS components SELECT * FROM component_template WHERE section IN (SELECT id FROM sections);
    SELECT * FROM sections;
    SELECT * FROM components;
    SELECT * FROM component_template_option WHERE component_template IN (SELECT id FROM components);
    DROP TEMPORARY TABLE IF EXISTS sections;
    DROP TEMPORARY TABLE IF EXISTS components;
END

1 个答案:

答案 0 :(得分:1)

使用// Retrieve file from S3... $image = Storage::disk('s3')->get($file); // Create temporary file with image content... $tmp = tmpfile(); fwrite($tmp, $image); // Reset file pointer to first byte so that we can read from it from the beginning... fseek($tmp, 0); // Upload temporary file to S3... \Stripe\FileUpload::create( array( "purpose" => "identity_document", "file" => $tmp ), array("stripe_account" => CONNECTED_STRIPE_ACCOUNT_ID) ); // Close temporary file and remove it... fclose($tmp); 语句时,如果表已经存在,SELECT部分​​将不会填充该表。

如果在存储过程中创建不在过程外部使用的临时表,则最好在过程的开头和结尾使用CREATE ... SELECT语句。结束的是程序清理完毕;起始的表确保先前执行中遗留的临时表(在丢弃它们之前出错/失败)不会干扰当前的执行。 你也可以将程序的主体包裹在TRY中,让滴剂在TRY之外,以确保滴剂出现,但这有点先进。

使用session / user / @变量时,请记住它们是数据库连接的全局变量,可以携带值;在可能的情况下使用本地DECLAREd变量(其范围不超出过程)。 Bonus:另外,尝试确保此类变量的名称和过程参数与过程中使用的表的字段名称不一致;它可能导致很难诊断问题。