2014-11-21 53 views
0

我正在研究一個有趣的查詢。有一個類似下面的表格,並且想要以3:2的比例基於login_status選擇30行。例如:在30人中,活躍用戶 - 應該是18,而非活躍用戶 - 應該是12.因此,對於每3個活躍用戶,我應該得到2個非活躍用戶,總計應該是30。Mysql以3:2的比例選擇查詢

有人可以提供一些想法如何實現所需的結果?

user_ref_id last_login   login_status 
     28369 2014-06-04 01:56:15 Not Active 
     11693 2013-10-09 00:19:17 Not Active 
     12566 2014-11-08 12:13:37 Active 
     9618 2014-11-15 17:04:47 Active 
     10270 2013-10-09 05:57:00 Not Active 
     20832 2014-01-24 07:24:46 Not Active 
     19297 2014-11-20 18:57:59 Active 
     14333 2014-01-23 23:24:37 Not Active 
     14785 2013-11-09 11:12:49 Not Active 
     18325 2014-04-12 22:54:10 Not Active 
     14748 2013-11-07 08:03:34 Not Active 
     20606 2014-05-20 04:30:35 Not Active 
     11812 2014-11-08 17:42:06 Active 
     15688 2013-11-18 04:43:23 Not Active 
     14949 2013-11-18 11:07:42 Not Active 
     18224 2014-11-08 16:30:41 Active 
     12202 2013-12-13 23:01:40 Not Active 
     20309 2014-03-13 06:37:51 Not Active 
     15089 2014-10-18 17:36:46 Not Active 
     10709 2014-09-24 22:31:11 Not Active 
     18539 2014-11-05 17:48:12 Active 
     11350 2013-10-07 23:50:51 Not Active 
     13134 2014-10-18 14:29:18 Not Active 
     13636 2014-09-12 17:20:03 Not Active 
     15246 2014-11-17 00:28:34 Active 
     16900 2013-11-25 03:28:38 Not Active 
     15584 2014-10-22 19:11:16 Active 
     16615 2014-10-14 17:55:39 Not Active 
     19610 2013-12-17 02:38:26 Not Active 
     20283 2014-09-27 07:34:51 Not Active 

回答

0

下面是使用工會的一種方式,它給人以不同的身份隨機行。

(select * from table1 where login_status='Active' 
order by rand() 
limit 18) 
union 
(select * from table1 where login_status='Not Active' 
order by rand() 
limit 12) 
+0

謝謝,但如果我找不到18個活動行?我的預期結果應該總共30行 – sam 2014-11-21 06:12:38