我的表格结构如下(含数据):

+------------------------------------+
|id    fname     category  city      |
|1     ram       cook      kathmandu |
|2     shyam     cook      lalitpur  |
|3     krishna   maid      patan     |
|4     jay       maid      kupondole |
|5     rajan     maid      ratnapark |
+------------------------------------+

查询应该同时返回两行(cook和maid),其中cook和maid是随机的。我该怎么做?

最佳答案

两种选择:

(SELECT * FROM TableName WHERE category='cook' ORDER BY rand() limit 1)
UNION ALL
(SELECT * FROM TableName WHERE category='maid' ORDER BY rand() limit 1)

参见SQL Fiddle中的结果。
或者
SELECT * FROM TableName
WHERE category IN ('cook','maid')
GROUP BY category
ORDER BY rand() limit 2

参见SQL Fiddle中的结果。
结果:
ID  FNAME   CATEGORY    CITY
1   ram     cook        kathmandu
5   rajan   maid        ratnapark

关于mysql - 如何选择2个随机类别数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23192285/

10-12 15:15