正确的限制联合和order by子句的语法与局部变量和mysql中的随机化:错误(1221)

时间:2014-01-20 15:26:11

标签: mysql union where-clause random-sample sql-limit

我正在尝试创建一个随机样本(30-70),如下所示:

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

#@total,@sample
#4090,9543.333331970

#发布此帖我可以通过这种通用语法

获取元素
PREPARE STMT FROM "SELECT * FROM tab_1 where predict_var ='2' or  predict_var ='4' ORDER BY RAND() LIMIT ? " ;
EXECUTE STMT USING @sample; # **THIS WORKS**

然而,虽然这两个条件的联合在这里,但它不起作用。它看起来像where_condition ='2'或者predict_var ='4'的条件与''或者用“”不起作用 - 我该如何使它起作用?

我的完整用例是这样的:

#This logic is my end-goal in retrieval of records
PREPARE STMT FROM " SELECT * FROM tab_1 WHERE predict_var = '4' or predict_var = '2' ORDER BY RAND() union (SELECT * FROM tab_1 WHERE predict_var = '0' or predict_var = '1' ORDER BY RAND() limit ?  )"
EXECUTE STMT USING @sample; # **does not work**

# This does not work either and gives "Error(1221) incorrect usage of union and order by

我也尝试过类似的东西(我认为这是非常有效的,因为这会创建临时表(我也可以选择视图,但重点是正确)

# using temp table/ could also get it via views - but doesn't work,nevertheless
#Alternate logic - but does not work either

PREPARE STMT FROM "SELECT * FROM tab_1 WHERE predict_var = '0' or predict_var = '1' ORDER BY RAND() limit ? " ; # Works

create table temp
select * from (EXECUTE STMT USING @sample ) ; # Error(1064)

SELECT * FROM tab_1 WHERE predict_var = '4' or predict_var = '2' ORDER BY  RAND() union select * from temp ; # of course does not work 

我模糊地理解这是关于移动工会和按条款订购 提示: - 请尽可能没有建议其他方法如此连接,请尽快解析为什么会失败。相关 - http://orkus.wordpress.com/2010/06/29/variable-limit-statement-in-mysql/

1 个答案:

答案 0 :(得分:0)

看起来我明白了!

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' limit ?  ) ORDER BY RAND() " ;
EXECUTE STMT USING @sample; # fetches a total of 13,633 records

*我唯一改变的就是从第一个查询中完全删除订单,然后将它放在合并后的查询之后(实际上是那么小的混乱!)。如果这不起作用,请随意明确 - 或者如果您有更好的建议,请轻推一下。