http://sqlfiddle.com/#!9/083f5d/1
它在上面的SQL查询中返回第6级而不是第1级。我需要在SQL查询中进行哪些更改,因此它提供了第一个等级,因为我使用WHERE条件来检查mpkid和roundpkid(WHERE mpkid = 37 AND roundpkid = 3)。
以下是查询:
SELECT mpkid, totalvote, rank
FROM (
SELECT mpkid, roundpkid, totalvote,
@n := IF(@g = totalvote, @n, @n + 1) rank,
@g := totalvote
FROM tr_msearch_vote_summary,
(SELECT @n := 0) i
ORDER BY totalvote DESC
) q
WHERE mpkid=37 AND roundpkid=3
我想要的是什么:
请先看看sqlfiddle。第3轮只有一个记录,它是37,所以我希望它应该显示mpkid#37和#3轮排名#1,但它排名第6。
答案 0 :(得分:2)
您在排名已完成后应用WHERE条件。我猜你想在WHERE应用后进行排名:
SELECT t.mpkid, t.roundpkid,
@n := IF(@g = t.totalvote, @n, @n + 1) rank,
@g := t.totalvote totalvote
FROM tr_msearch_vote_summary t, (SELECT @n := 0) i
WHERE t.mpkid=37 AND t.roundpkid=3
ORDER BY t.totalvote DESC
您还应该初始化@g以确保它不会在另一个查询中预设:
SELECT t.mpkid, t.roundpkid,
@n := IF(@g = t.totalvote, @n, @n + 1) rank,
@g := t.totalvote totalvote
FROM tr_msearch_vote_summary t, (SELECT @n := 0, @g := NULL) i
WHERE t.mpkid=37 AND t.roundpkid=3
ORDER BY t.totalvote DESC
<强>更新强>
如果你想要按轮次分组,然后简单地按照mpkid进行选择,这是一个更强大的查询:
SELECT mpkid,
roundpkid,
totalvote,
rank
FROM (
SELECT t.mpkid,
@n := CASE
WHEN @r = t.roundpkid AND @g = t.totalvote THEN @n
WHEN @r = t.roundpkid THEN @n + 1
ELSE 1
END rank,
@r := t.roundpkid roundpkid,
@g := t.totalvote totalvote
FROM tr_msearch_vote_summary t, (SELECT @n := 0, @g := NULL, @r := NULL) i
ORDER BY t.roundpkid, t.totalvote DESC
) r
WHERE mpkid = 37;
请注意,您无需提供roundpkid。 See updated fiddle
答案 1 :(得分:1)
请尝试此查询,
SELECT mpkid, totalvote, rank
FROM (
SELECT mpkid, roundpkid, totalvote,
@n := IF(@g = totalvote, @n, @n + 1) rank,
@g := totalvote
FROM tr_msearch_vote_summary,
(SELECT @n := 0) i
WHERE roundpkid=3
ORDER BY totalvote DESC
) q
WHERE mpkid=37
这是你更新的sqlfiddle。 http://sqlfiddle.com/#!9/083f5d/9