2014-02-25 48 views
2

关于如何使用Mysql按组选择最小/最大或前n条记录,有几个很好的条目。我的做法无可否认是行人(我明白这一点),但我想知道是否有更好的方式直觉地让我清楚。一个特别丑陋的地方是需要硬编码所需的计数(1000),因为不能将set LIMIT_value := 1000;作为查询中的参数。mysql:按组选择最多n条记录的最有效方式

所以我的问题是:是否有更好,更费力的方式来选择从给定的段1000记录?奖金的问题(这可以通过sed处理并传入mysql ...)我可以参数化1000条记录请求吗?

快速背景:我正在考虑给予两个不同的报价,但没有正确随机化的两个客户群组。我针对不同的要约价格水平对后续活动进行分析。

使用新近度(R,自上次购买后12米或更多12米)和频率(F,1次)随机匹配客户(第一队列中的一个客户与第二队列中的一个客户买方或2x +)分组来控制营销活动时未知的不同潜在客户群。对于在联系时识别为新文件的客户,R和F值均为“NA”,并构成另一个分组级别。谢谢。

/* _lp_stp: low price sample, _hp_stp: high price sample */ 

drop table if exists _lp_stp; 
create table _lp_stp as 
(select ID,price,rbin,fbin from _lp where rbin='NA' and fbin='NA' limit 1000) 
union 
(select ID,price,rbin,fbin from _lp where rbin='NA' and fbin='1x' limit 1000) 
union 
(select ID,price,rbin,fbin from _lp where rbin='NA' and fbin='2x+' limit 1000) 
union 
(select ID,price,rbin,fbin from _lp where rbin='12m' and fbin='NA' limit 1000) 
union 
(select ID,price,rbin,fbin from _lp where rbin='12m' and fbin='1x' limit 1000) 
union 
(select ID,price,rbin,fbin from _lp where rbin='12m' and fbin='2x+' limit 1000) 
union 
(select ID,price,rbin,fbin from _lp where rbin='12m+' and fbin='NA' limit 1000) 
union 
(select ID,price,rbin,fbin from _lp where rbin='12m+' and fbin='1x' limit 1000) 
union 
(select ID,price,rbin,fbin from _lp where rbin='12m+' and fbin='2x+' limit 1000); 


drop table if exists _hp_stp; 
create table _hp_stp as 
(select ID,price,rbin,fbin from _hp where rbin='NA' and fbin='NA' limit 1000) 
union 
(select ID,price,rbin,fbin from _hp where rbin='NA' and fbin='1x' limit 1000) 
union 
(select ID,price,rbin,fbin from _hp where rbin='NA' and fbin='2x+' limit 1000) 
union 
(select ID,price,rbin,fbin from _hp where rbin='12m' and fbin='NA' limit 1000) 
union 
(select ID,price,rbin,fbin from _hp where rbin='12m' and fbin='1x' limit 1000) 
union 
(select ID,price,rbin,fbin from _hp where rbin='12m' and fbin='2x+' limit 1000) 
union 
(select ID,price,rbin,fbin from _hp where rbin='12m+' and fbin='NA' limit 1000) 
union 
(select ID,price,rbin,fbin from _hp where rbin='12m+' and fbin='1x' limit 1000) 
union 
(select ID,price,rbin,fbin from _hp where rbin='12m+' and fbin='2x+' limit 1000); 

回答

0

声明:该查询只是为了看起来更简单,但性能可能很差,尤其是如果您正在处理大表。和从未曾经我想在我的生产DB这样的查询,

select ID,price,rbin,fbin 
from _lp 
inner join (
select substring_index(substring_index(group_concat(id order by id asc),",", 1000),",",-1) as id, fbin, rbin 
where fbin in (...) and rbin in (...) 
group by fbin, rbin 
where rbin='12m+' and fbin='2x+') as t 
on t.rbin = _lp.rbin and t.fbin = _lp.fbin and t.rbin <= _lp.id 

查询的一点解释:

  1. 子查询得到升序第1000号的ID。举例来说,如果你有5000条记录,子查询给予4000如果没有指定分组(我增加了一个额外的组通过,以适应每个组)
  2. 外部查询得到,然后取谁拥有值小于给定记录的所有记录
+0

谢谢cjg。我不得不仔细地浏览你的代码,因为它对我来说并不直观。我绝对会跟进。 – user2105469