gpt4 book ai didi

php - 使用特定ID对mysql进行排名

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:09 26 4
gpt4 key购买 nike

我有这个问题

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 的排名,例如,如果我想要 ID 134 的排名

我试过类似的东西

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

最佳答案

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

关于php - 使用特定ID对mysql进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38397517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com