我有这个查询
SELECT concours_photo_like.id , COUNT(concours_photo_like.id) AS nb_like , (@rank := @rank + 1) AS rank
FROM ( SELECT @rank := 0 ) as r , concours_photo_like
JOIN concours_photo ON concours_photo.id = concours_photo_like.id_concours_photo
WHERE concours_photo.id_concours = 67
GROUP BY concours_photo_like.id_concours_photo
结果
| id | nb_like | rank |
|--------|------------|------|
| 110 | 2 | 2 |
| 104 | 3 | 1 |
| 134 | 1 | 4 |
| 176 | 1 | 5 |
| 113 | 2 | 3 |
如果我想要ID 134的等级
,我如何获得特定ID的等级我试过像
这样的东西SELECT concours_photo_like.id , COUNT(concours_photo_like.id) AS nb_like , (@rank := @rank + 1) AS rank
FROM ( SELECT @rank := 0 ) as r , concours_photo_like
JOIN concours_photo ON concours_photo.id = concours_photo_like.id_concours_photo
WHERE concours_photo.id_concours = 67
AND concours_photo_like.id = 134
GROUP BY concours_photo_like.id_concours_photo
但结果是
| id | nb_like | rank |
|--------|------------|------|
| 134 | 1 | 1 |
,结果应为4而不是1
答案 0 :(得分:2)
如何用另一个SELECT
语句包装原始查询,然后按id
进行过滤,如下所示:
SELECT * FROM
(SELECT concours_photo_like.id , COUNT(concours_photo_like.id) AS nb_like , (@rank := @rank + 1) AS rank
FROM ( SELECT @rank := 0 ) as r , concours_photo_like
JOIN concours_photo ON concours_photo.id = concours_photo_like.id_concours_photo
WHERE concours_photo.id_concours = 67
GROUP BY concours_photo_like.id_concours_photo) AS nb
WHERE nb.id = 134
执行此查询可能有更优雅的方式,但这就是现在想到的。
答案 1 :(得分:2)
MySQL在为选择列表中的用户变量赋值之前执行where
子句。
您必须过滤having
子句或将查询包装到子查询中并在外部查询中进行过滤。
有:
SELECT concours_photo_like.id , COUNT(concours_photo_like.id) AS nb_like , (@rank := @rank + 1) AS rank
FROM ( SELECT @rank := 0 ) as r , concours_photo_like
JOIN concours_photo ON concours_photo.id = concours_photo_like.id_concours_photo
WHERE concours_photo.id_concours = 67
GROUP BY concours_photo_like.id_concours_photo
HAVING concours_photo_like.id = 134
子查询:
SELECT *
FROM
(SELECT concours_photo_like.id , COUNT(concours_photo_like.id) AS nb_like , (@rank := @rank + 1) AS rank
FROM ( SELECT @rank := 0 ) as r , concours_photo_like
JOIN concours_photo ON concours_photo.id = concours_photo_like.id_concours_photo
WHERE concours_photo.id_concours = 67
GROUP BY concours_photo_like.id_concours_photo
) t1
WHERE t1.id = 134