我的表结构如下(带数据):
+------------------------------------+
|id fname category city |
|1 ram cook kathmandu |
|2 shyam cook lalitpur |
|3 krishna maid patan |
|4 jay maid kupondole |
|5 rajan maid ratnapark |
+------------------------------------+
查询应该使用随机烹饪和女佣一次返回2行(cook和maid)。我怎么能这样做?
答案 0 :(得分:2)
两种选择:
(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
答案 1 :(得分:1)
select fname
from table
where category="cook"
order by RAND()
LIMIT 1
UNION
select fname
from table
where category="maid"
order by RAND()
LIMIT 1
答案 2 :(得分:1)
子查询负责查找随机ID
SELECT *
FROM mytable
WHERE id IN
(SELECT round(rand()*(max(id)-min(id)+1))+min(id)
FROM mytable
GROUP BY category);