SQL 中的ORDER BY

MySQL中 IN 不能和LIMIT一起用

还是上jie那个学生表,我现在想查询cid为02 的前三名学生的总成绩

SELECT SUM(s_score)
  FROM score
 WHERE s_score IN (SELECT s_score
FROM score
 WHERE c_id = '02'
 ORDER BY s_score DESC
 LIMIT 3);

this version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

解决方案1:再嵌套一次

 

SELECT SUM(s_score)
  FROM score
 WHERE s_score IN (SELECT s_score FROM(
				SELECT s_score
				 FROM score
				WHERE c_id = '02'
				ORDER BY s_score DESC
				LIMIT 3) AS t1);

解决方案2:把它放在from里面不涉及in

SELECT SUM(t1.s_score)
  FROM (
SELECT s_score
FROM score
 WHERE c_id = '02'
 ORDER BY s_score DESC
 LIMIT 3) t1;

当然我也可以不用limit

-- cid的为02的前三名
SELECT SUM(t1.s_score)
  FROM (
SELECT s1.s_id,s1.s_score
  FROM Score s1
 WHERE s1.c_id = '02'
   AND (SELECT COUNT(*) FROM Score s2
		 WHERE s1.c_id = s2.c_id
           AND s2.s_score > s1.s_score) < 3) AS t1;

我也不知道为什么以前说表表达式不能用order by但这里确实可以了

等待大神回复 

 

 

 

你可能感兴趣的:(Datawhale之MySQL)