Storing the results of a prepared statement as a table in mysql?

江枫思渺然 提交于 2019-12-22 08:25:15

问题


Is it possible to store the result of a prepared table in mysql ?

My use case is -: I am creating two variables based on certain conditions of the source table, then fetching the randomized rows, based on this criteria. Since I have 10 of such tables, should I be 1st joining them and then doing this randomization on the "overall" passing/filtering criteria (See also @total below, which is my main criteria, PER table)

set @total=(select count(*) from tab_1 where predict_var ="4" or predict_var ="2" ) ;
set @sample= ( select @total*(70/30))  ;

PREPARE STMT FROM " SELECT * FROM tab_1 WHERE predict_var = '4' or predict_var = '2'  union 
(SELECT * FROM tab_1 WHERE predict_var = '0' or predict_var = '1' ORDER BY RAND() limit ?  )" ;
EXECUTE STMT USING @sample;

After I have Executed this statement - I want to be storing these rows, for retrieval later, preferably in form of a table. I would like to do something like this

# incorrect syntax, but I would like something similar 
create table tab_derived_1
select * from 
EXECUTE STMT USING @sample;

Tip : +1 for additionally mentioning, why this does not work with prepared Statements.


回答1:


Put the create table in the statement:

PREPARE STMT FROM "CREATE TABLE tab_derived_1 SELECT * FROM tab_1 WHERE predict_var = '4'   or predict_var = '2'  union 
(SELECT * FROM tab_1 WHERE predict_var = '0' or predict_var = '1' ORDER BY RAND() limit ?  )" ;
EXECUTE STMT USING @sample;

And if you want to return the results, not just store them in a table, just do a final

SELECT * FROM tab_derived_1


来源:https://stackoverflow.com/questions/21310085/storing-the-results-of-a-prepared-statement-as-a-table-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!