我需要一些关于MySQL SELECT语句的帮助。不幸的是,此声明无法正常工作。它似乎根据学校名称的字母顺序排名,而不是reading_percent_proficient_and_advanced。我该如何解决?
SET @rank=0;
SELECT @rank:=@rank+1 as rank,
sy.formatted_school_name,
FLOOR(d.reading_percent_proficient + d.reading_percent_advanced) AS reading_percent_proficient_and_advanced
FROM d_test_scores AS d,
sy_2010_2011_school_type AS sy
WHERE sy.school_id = d.school_id
AND sy.school_group = 'public school'
AND sy.school_type ='elementary'
ORDER BY reading_percent_proficient_and_advanced DESC
如果我取消加入,那么这句话给了我正确的排名(但我当时没有学校名称):
SET @rank=0;
SELECT @rank:=@rank+1 as rank,
d.school_id,
FLOOR(d.reading_percent_proficient + d.reading_percent_advanced) AS reading_percent_proficient_and_advanced
FROM d_test_scores AS d
ORDER BY reading_percent_proficient_and_advanced DESC;
我的加入有什么问题?
答案 0 :(得分:1)
(推测)我相信在强制执行ORDER BY排序之前计算排名。在原始查询中,恰好在ORDER BY之前按照您想要的顺序返回结果,从而排名正确,在高级查询中,结果最初以不同的顺序返回。
尝试将排名添加到学校名称和熟练程度等级的已订购集(子查询)中。
答案 1 :(得分:1)
我实际上没有看到任何JOIN关键字,试试这个吗?
SET @rank=0;
SELECT @rank:=@rank+1 as rank,
sy.formatted_school_name,
FLOOR(d.reading_percent_proficient + d.reading_percent_advanced) AS reading_percent_proficient_and_advanced
FROM d_test_scores d JOIN sy_2010_2011_school_type sy on sy.school_id = d.school_id
WHERE sy.school_group = 'public school'
AND sy.school_type ='elementary'
ORDER BY reading_percent_proficient_and_advanced DESC
只是一个猜测。