2014-02-25 37 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

相關問題