在一个查询中命令混合混合mysql搜索结果?

时间:2010-04-19 11:28:05

标签: sql mysql

这个问题很容易修复客户端。但是为了性能,我想直接将它做到数据库。

LIST a
+------+-------+-------+
| name | score | cre   |
+------+-------+-------+
| Abe  | 3     | 1     |
| Zoe  | 5     | 2     |
| Mye  | 1     | 3     |
| Joe  | 3     | 4     |

想要检索已连接的混合结果而无需重复。

Zoe (1st highest score)
Joe (1st last submitted)
Abe (2nd highest score)
Mye (2nd last submitted)
...

Clientside我自己进行每次搜索并逐步完成。 但在100.000+上它变得尴尬。能够使用LIMIT功能可以减轻很多事情!

SELECT name FROM a ORDER BY score DESC, cre DESC;
SELECT name FROM a ORDER BY cre DESC, score DESC;

1 个答案:

答案 0 :(得分:1)

MySQL不提供像ROW_NUMBER这样的分析函数。

实现这一目标的一种方法是将两个Order By不同的查询连接在一起:

Select s.name, s.score_num, c.cre_num
From
(
    Select name, @score_num := @score_num + 1 As score_num
    From your_table, ( SELECT @score_num := 0 ) v
    Order By score Desc
) s
Join
(
    Select name, @cre_num := @cre_num + 1 As cre_num
    From your_table, ( SELECT @cre_num := 0 ) v
    Order By cre Desc
) c
On ( c.name = s.name )

返回

name  score_num  cre_num
Joe           3        1
Mye           4        2
Zoe           1        3
Abe           2        4

这是你想要的吗?