Php Laravel+mysql:可以创建/更新临时表,但不能从以下位置选择:

Php Laravel+mysql:可以创建/更新临时表,但不能从以下位置选择:,php,mysql,laravel,temp-tables,Php,Mysql,Laravel,Temp Tables,我可以创建一个临时表,但当我尝试从中选择时,它会说该表不存在。我认为这是因为DB::statement和DB::select在某种程度上与数据库有不同的会话,但我不确定如何修复它 如何在同一脚本中创建临时表、插入临时表以及从临时表中选择临时表 下面是tinker的输出,演示了该问题: DB::select("select count(*) from users"); //12 DB::statement("create temporary table tempUsers like users")

我可以创建一个临时表,但当我尝试从中选择时,它会说该表不存在。我认为这是因为DB::statement和DB::select在某种程度上与数据库有不同的会话,但我不确定如何修复它

如何在同一脚本中创建临时表、插入临时表以及从临时表中选择临时表

下面是tinker的输出,演示了该问题:

DB::select("select count(*) from users"); //12
DB::statement("create temporary table tempUsers like users"); //true
DB::statement("insert into tempUsers (id,email) VALUES (1, 'joe@example.com')"); //true
在所选会话上似乎不存在

DB::select("select count(*) from tempUsers"); 
使用消息“SQLSTATE[42S02]:Base照亮\Database\QueryException 未找到表或视图:1146表“db.tempUsers”不存在SQL: 从tempUsers菜单中选择count*

在语句会话中仍然存在

DB::statement("insert into tempUsers (id,email) VALUES (2, 'bob@example.com')"); //true
DB::statement("insert into tempUsers (id,email) VALUES (1, 'joe@example.com')"); 
带有消息“SQLSTATE[23000]”的Illumb\Database\QueryException: 完整性约束冲突:密钥的1062个重复条目“1” “主”SQL:插入临时用户id、电子邮件值 1,'bob@example.com

我使用$table->temporary和Blueprint得到了相同的行为,即

使用Laravel5.4、MySQL 5.6


当我连接到laravel外部的DB时,我可以很好地操纵和选择临时表。如果在存储过程中创建临时表,则一旦存储过程完成,它就会被销毁

临时表的范围很重要,仅对特定用户可见。临时表以英镑符号“”或“@”开头,这非常重要,因为您似乎遗漏了这一部分

因此,如果将迁移调整为:

Schema::create('#tmpTest', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
});
然后运行:

php artisan migrate:fresh
要在临时表中插入数据,请执行以下操作:

\DB::语句插入到tmpTest id中,名称值为1, 'joe@example.com';

要使用“选择”获取这些数据,请执行以下操作:

$a=DB::选择'select*fromtmptest'; dd$a

结果是:


原来问题是由我们的设置引起的。我们使用一个数据库进行写入,另一个用于读取。writer数据库被复制到read数据库,但是,因为它是一个临时表,并且被锁定到与writer的当前会话

如果使用Laravel 5.5+,解决方案是设置数据库连接。这使得写入程序在任何写入之后都被视为读取器,从而绕过复制延迟问题

因为我现在坚持使用Laravel5.4,所以我的解决方案是创建一个标准表,但将其视为临时表,并将其放在方法的末尾

DB::select("select count(*) from users"); //12

//use uniqid to ensure a unique tablename since it is now in the global namespace
$tableName=uniqid('tempUsers'); 

DB::unprepared("create table $tableName like users"); //true
DB::statement("insert into tempUsers (id,email) VALUES (1, 'joe@example.com')"); //true
DB::select("select count(*) from $tableName"); //1
//...do stuff with temp table
//...
Schema::drop($tableName);
// return

嘿,谢谢你的回复。我不是在存储过程中创建它,所以这不是一个因素。mysql不使用散列来表示临时表(mssql可能会使用),因此在我的环境中,您的代码将执行,但它将创建一个名称中带有文本散列标记的普通表,而不是临时表,因此这并不能回答问题
DB::select("select count(*) from users"); //12

//use uniqid to ensure a unique tablename since it is now in the global namespace
$tableName=uniqid('tempUsers'); 

DB::unprepared("create table $tableName like users"); //true
DB::statement("insert into tempUsers (id,email) VALUES (1, 'joe@example.com')"); //true
DB::select("select count(*) from $tableName"); //1
//...do stuff with temp table
//...
Schema::drop($tableName);
// return