簡體   English   中英

MySQL從表中按列選擇x條記錄

[英]MySQL select x number of records from table by column

可能是有史以來最差的頭銜。 我有一張3列的表格

id | name | type
1  | John | 1
2  | Sam  | 1
3  | Bob  | 2
4  | Joe  | 2
5  | Al   | 3
6  | Paul | 3

我需要選擇3個具有不同類型的隨機人

有效的輸出將是

id | name | type
1  | John | 1
3  | Bob  | 2
6  | Paul | 3

無效的輸出將是

id | name | type
3  | Bob  | 2
5  | Al   | 3
6  | Paul | 3

我以為我能做的是

SELECT id, name, type FROM table WHERE type = 1
UNION
SELECT id, name, type FROM table WHERE type = 2
UNION
SELECT id, name, type FROM table WHERE type = 3

但這實際上是不可能的,因為這只是一個簡化的示例,在實際代碼中,我還有很多列可供選擇和執行聯接,如果以這種方式進行操作,則將很難維護。 有什么建議么?

這是使用變量的方法。 大概,您需要每種類型的隨機記錄:

select id, name, type
from (select t.*,
             (@rn := if(@t = type, @rn + 1,
                        if(@t := type, 1, 1)
                       )
             ) as seqnum
      from table t cross join
           (select @t := 0, @rn := 0) vars
      order by type, rand()
     ) t
where seqnum = 1;

為什么不嘗試與分組依據。

 select id,name,type from table group by type order by rand() limit 0,XXX

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM