从数据库表MYSQL中选择2个随机成员

时间:2013-01-30 11:44:04

标签: php mysql performance

我在下面有一个查询。在执行它时,它返回所有结果,我可以看到每个成员的多个记录。

我想选择随机选择的两个成员的个人资料,而不会出现任何性能问题。

SELECT
  a.memberid,
  a.category_id,
  a.content,
  a.count_cid,
  a.importance
FROM tb_profilingdata a,
  tb_member b
WHERE a.memberid = b.memberid
    AND a.category_id IN($catstr)
    AND a.memberid NOT IN('$mid',$seen)
    AND b.gender = 'male'
ORDER BY a.memberid, a.category_id

Result of this query

我尝试了一些查询来选择一个随机记录

SELECT
  r1.memberid
FROM tb_profilingdata AS r1
  JOIN (SELECT
      (RAND() * (SELECT MAX(DISTINCT(memberid)) FROM tb_profilingdata)) AS memberid) AS r2
WHERE r1.memberid >= r2.memberid
ORDER BY r1.memberid ASC
LIMIT 1

但它从 tb_profilingdata 中选择了总共1条记录,而我想要一个随机选择的成员的记录。

我使用 tb_member 尝试了相同的查询,但是tb_member中的成员可能没有 tb_profilingdata中的条目..

请以最少的性能问题向我建议。

2 个答案:

答案 0 :(得分:4)

可能会对你有所帮助:

SELECT [something] FROM [source] WHERE [conditions] ORDER BY RAND() LIMIT 2

答案 1 :(得分:0)

除非您提供一些示例数据

,否则此查询未经测试
SELECT
  a.memberid,
  a.category_id,
  a.content,
  a.count_cid,
  a.importance
FROM tb_profilingdata a
  left join (select
           memberid
         from tb_member
         group by memberid
         order by rand()) b
    on a.memberid = b.memberid
WHERE a.category_id IN($catstr)
    AND a.memberid NOT IN('$mid',$seen)
    AND b.gender = 'male'
ORDER BY a.memberid, a.category_id