如何在给定查询中使用LIMIT

时间:2016-06-30 11:10:17

标签: mysql

    $sql = "
SELECT *
FROM teacher_uploads
where view_counts in (SELECT view_counts
                      from teacher_uploads
                      ORDER BY view_counts DESC
                     ) and
      subject_id = $subject_id";

现在我想获取所有最大view_counts  限制为2

2 个答案:

答案 0 :(得分:1)

您可以使用join

SELECT tu.*
FROM teacher_uploads tu JOIN
     (SELECT view_counts
      FROM teacher_uploads
      ORDER BY view_counts DESC
      LIMIT 2
     ) ttu
     ON tu.view_counts = ttu.view_counts
WHERE subject_id = $subject_id;

注意:您可能还需要子查询中的WHERE子句。但是,这不是您问题中的查询。

答案 1 :(得分:-2)

$sql = "
SELECT * 
  FROM teacher_uploads 
 WHERE view_counts IN (SELECT view_counts 
                         FROM teacher_uploads 
                        ORDER 
                           BY view_counts DESC )  
   AND subject_id = $subject_id 
 LIMIT 2"