我有一个MySQL语句,可以选择一个名字并进行排名。
SELECT t.name,
(SELECT COUNT(*)
FROM my_table1 z
WHERE z.type LIKE '%Blue%'
AND t.type LIKE '%Blue%'
AND (z.score1+ z.score2 + z.score3 + z.score4) >= (t.score1+ t.score2 + t.score3 + t.score4)) AS rank
FROM my_table1 t, my_table2 d
WHERE d.name = t.name
AND t.status != 'unknown'
AND t.type = 'Blue'
AND d.area_served = '$area_id'
ORDER BY rank ASC
但是,我还需要知道排名的计算数量。例如,在X中排名第4位。
如何计算排名子查询中的总行数?我需要这一点的计数:
(SELECT COUNT(*)
FROM my_table1 z
WHERE z.type LIKE '%Blue%' AND t.type LIKE '%Blue%'
AND (z.score1+ z.score2 + z.score3 + z.score4) >= (t.score1+ t.score2 + t.score3 + t.score4)) AS rank
谢谢。
-Laxmidi
答案 0 :(得分:3)
您可以再添加一个子查询 - 它将与现有子查询相同但没有AND (z.score1+ z.score2 + z.score3 + z.score4) >= (t.score1+ t.score2 + t.score3 + t.score4)
条件:
SELECT t.name,
(SELECT COUNT(*)
FROM my_table1 z
WHERE z.type LIKE '%Blue%'
AND t.type LIKE '%Blue%'
AND (z.score1+ z.score2 + z.score3 + z.score4) >= (t.score1+ t.score2 + t.score3 + t.score4)) AS rank,
// new subquery
(SELECT COUNT(*)
FROM my_table1 z
WHERE z.type LIKE '%Blue%'
AND t.type LIKE '%Blue%') as max_rank
FROM my_table1 t, my_table2 d
WHERE d.name = t.name
AND t.status != 'unknown'
AND t.type = 'Blue'
AND d.area_served = '$area_id'
ORDER BY rank ASC
答案 1 :(得分:1)
您可以使用相同的子选择而不进行分数比较:
SELECT t.name,
(SELECT COUNT(*)
FROM my_table1 z
WHERE z.type LIKE '%Blue%'
AND t.type LIKE '%Blue%'
AND (z.score1+ z.score2 + z.score3 + z.score4) >= (t.score1+ t.score2 + t.score3 + t.score4)) AS rank,
(SELECT COUNT(*)
FROM my_table1 z
WHERE z.type LIKE '%Blue%'
AND t.type LIKE '%Blue%') AS rankOutOf
FROM my_table1 t, my_table2 d
WHERE d.name = t.name
AND t.status != 'unknown'
AND t.type = 'Blue'
AND d.area_served = '$area_id'
rankOutOf
列返回排名查询中考虑的候选人数。
答案 2 :(得分:0)
我不确定我是否理解,但我认为你应该在子查询中包含FOUND_ROWS()。
(SELECT COUNT(*),FOUND_ROWS()FROM my_table1 z WHERE z.type LIKE'%Blue%' AND t.type LIKE'%Blue%'AND (z.score1 + z.score2 + z.score3 + z.score4)> =(t.score1 + t.score2 + t.score3 + t.score4))AS等级,数字
您可以在此处找到更多信息:http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
答案 3 :(得分:0)
我在理解你的问题时遇到了一些麻烦,但我会抓住它。
这部分为您提供特定的等级编号(例如4):
(SELECT COUNT(*)
FROM my_table1 z
WHERE z.type LIKE '%Blue%' AND t.type LIKE '%Blue%'
AND (z.score1+ z.score2 + z.score3 + z.score4) >= (t.score1+ t.score2 + t.score3 + t.score4)) AS rank
因此,为了找到该子查询的总行数,您只需要删除WHERE
子句。我不确定你是否需要删除WHERE
子句中的所有内容,可能仅仅是类型,还是仅仅是分数?
如果您要将多个行组合在一起,我会使用GROUP BY
,然后根据需要使用COUNT
。