Mysql - 按2级排序

时间:2009-07-08 12:02:33

标签: mysql sql-order-by

我有一张物品表。 item有id,得分1,得分2。

我想选择12个已知项目(使用WHERE id IN (....)),然后按得分1和得分2的排名之和进行排序。如果按顺序排列了12个项目,则排名是分数的位置。

我怎样才能在mysql中执行此操作?

修改

经过4个回答后,我发现解决方案可能比我预期的要复杂得多。所以让我以另一种方式提出这个问题。

如果我使用select *, [calculation] from table where id IN (odered list of ids)。我可以以某种方式使用[calculation]中原始有序的ID列表中每个id的位置吗?

3 个答案:

答案 0 :(得分:2)

出乎我的意料:

CREATE TEMPORARY TABLE t_1(score_1_rank INT AUTO_INCREMENT, id)
CREATE TEMPORARY TABLE t_2(score_2_rank INT AUTO_INCREMENT, id)

INSERT INTO t_1(id)
SELECT id
FROM items i
WHERE id IN () 
ORDER BY score_1

INSERT INTO t_2(id)
SELECT id
FROM items i
WHERE id IN ()
ORDER BY score_2

SELECT ...
FROM   items i
INNER JOIN t_1 t1
  ON t1.id = i.id
INNER JOIN t_2 t2
  ON t2.id = i.id
ORDER BY t1.rank + t2.rank

我是否正确理解了您的要求?

答案 1 :(得分:0)

这是你想要做的吗?

SELECT
(CAST(score1 AS INT) + CAST(score2 AS INT)) AS rank
FROM items
WHERE id IN(...)
ORDER BY rank DESC

答案 2 :(得分:0)

SELECT id, score1, score2, 
    r1.rank AS rank1, 
    r2.rank AS rank2, 
    (r1.rank + r2.rank) rankSum
FROM items i
INNER JOIN (
    SELECT @rank := @rank + 1 AS rank, id
    FROM items, (SELECT @rank :=0) AS r
    ORDER BY score1
) AS r1 ON r1.id = i.id
INNER JOIN (
    SELECT @rank := @rank + 1 AS rank, id
    FROM items, (SELECT @rank :=0) AS r
    ORDER BY score2
) AS r2 ON r2.id = i.id
ORDER BY rankSum

但我怀疑这会以某种方式非常有效,不仅因为查询无法使用查询缓存。