多次加入后在mysql中找到排名

时间:2016-04-07 01:15:42

标签: php mysql join

我试图通过用户获得的总积分找到Ecto.ConstraintError at DELETE /users/2 constraint error when attempting to delete model: * foreign_key: posts_user_id_fkey 。我确实有这个问题,但没有知道如何继续。

rank

3 个答案:

答案 0 :(得分:3)

你可以尝试这个:

SET
    @prev = 0,
    @curr = 0,
    @rank = 1,
    @i = 1;

SELECT
    @prev := @curr,
    @rank := IF(
        @prev = @curr,
        @rank,
        @rank + @i
    ) AS rank,
    IF(
        @prev != SUM(wp_grank.points),
        @i := 1,
        @i := @i + 1
    ) AS counter,
    wp_grank.ID,
    wp_grank.competitor_ID ,
    wp_grank.tournament_ID ,
    wp_grank.academy_ID ,
    wp_grank.division_ID,
    wp_competitor.first_name,
    wp_competitor.last_name,
    wp_competitor.global_ID,
    wp_divisions.gender,
    IF(
        wp_divisions.age_level IN ('Tiny Kids','Kids','Pre Teen','Teen'),
        CONCAT('(',wp_divisions.gender,')'),
        ''
    ) as filterGender,
    wp_tournaments.`name` as tournament_name,
    wp_divisions.name as dname,
    CONCAT_WS(
        ' >> ',
        wp_divisions.division_type,
        wp_divisions.experience_level,
        wp_divisions.age_level,
        wp_divisions.weight_class,
        wp_divisions.gender
    ) as division,
    wp_academies.`name` as academy,
    @curr := SUM(wp_grank.points) as `totalPoints`
FROM
    `wp_grank`
    LEFT JOIN wp_competitor ON wp_grank.competitor_ID = wp_competitor.ID
    LEFT JOIN wp_tournaments ON wp_grank.tournament_ID = wp_tournaments.ID
    LEFT JOIN wp_academies ON wp_grank.academy_ID = wp_academies.ID
    LEFT JOIN wp_divisions ON wp_grank.division_ID = wp_divisions.ID
WHERE
    wp_divisions.ID IN (2)
    AND YEAR(wp_tournaments.tournament_date)=2015
GROUP BY wp_competitor.ID
ORDER BY
    `totalPoints` DESC,
    wp_competitor.`last_name` ASC;  

注意:

  • 对于您需要tied条记录的排名,我使用session variable来定义排名将increaseretain基于之前的值。< / LI>

干杯

答案 1 :(得分:2)

我猜您只想在查询中添加排名列。如果是这样的话:

set @rank = 0

select (@rank := @rank + 1) as rank, 
       . . .

有时,变量不能与group by一起使用,因此您需要一个子查询:

select (@rank := @rank + 1) as rank, q.*
from (<your query here>) q cross join
     (select @rank := 0) params;

答案 2 :(得分:0)

试试这个:

定义一个变量:

SET @row_number = 0;

然后打包您的查询:

select @row_number:=@row_number + 1) AS rank, [all the other columns here]
from ( [your nasty query here ] ) as myNastyNastyQuery;

请确保您的订购是在讨厌的查询中完成的。 LOL