使用LEFT JOIN在查询中请求随机行

时间:2013-03-20 14:48:51

标签: mysql

我有2个表来进行测验:“问题”和“答案”。每个问题都有4个答案。我想请求50个随机问题。我尝试了这个,但它返回的问题不到50个。

(我需要所有50个问题和200个答案的所有字段)。

SELECT Q.*, A.* FROM questions Q
LEFT JOIN answers A ON Q.pid = A.pid
WHERE Q.pid >= RAND() * (SELECT MAX(pid) FROM questions)
AND  Q.lid IN $array
GROUP BY Q.pid
LIMIT 50

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

 SELECT y.* 
   FROM 
      ( SELECT * 
          FROM questions 
         ORDER 
            BY RAND() LIMIT 2
      ) x 
   JOIN answers y 
     ON y.question_id = x.question_id 
  ORDER  
     BY x.question_id;