从积分表中获取参赛者的排名以及其他和嵌套条件

时间:2017-11-20 17:16:04

标签: mysql select optimization greatest-n-per-group

我们正在尝试使用以下选择查询来计算特定比赛的参赛者等级。 GROUP_CONCAT解决方法实际上是针对类似问题在此处提供的解决方案。

然而,当我们添加更多条件时,查询变得冗长,不整洁并且不是DRY,我认为我们必须为GROUP_CONCAT子查询重复相同的条件。

如何优化?或者,如果以编程方式计算排名和检查条件然后填充数据库的解决方案,在这种情况下是最佳解决方案吗?

SELECT *,
  -- Get the rank of contestants
  FIND_IN_SET(`id`, (
      SELECT GROUP_CONCAT(`id` ORDER BY `points` DESC, `created`)
      FROM `contestants` `c2`

      -- The following query is exactly the same as the on in the main query bellow.
      WHERE `contest_id`=:contest_id
        AND EXISTS (
          SELECT `user_id`
          FROM `item`
          WHERE `user_id`=`c2`.`user_id`
            AND `product_id` IN (
              SELECT `id`
              FROM `product`
              WHERE `price`<=:max_price
                AND `available`=:available
            )
        )
        AND `state`=:state
        -- ---------------------------------------------------------------------------

    )
  ) AS `rank`
FROM `contestants`

-- ---------------------------------------------------------------------------
WHERE `contest_id`=:contest_id
  AND EXISTS (
    SELECT `user_id`
    FROM `item`
    WHERE `user_id`=`c2`.`user_id`
      AND `product_id` IN (
        SELECT `id`
        FROM `product`
        WHERE `price`<=:max_price
          AND `available`=:available
      )
  )
  AND `state`=:state
-- ---------------------------------------------------------------------------

ORDER BY `rank` ASC
LIMIT 10

0 个答案:

没有答案