1

我有一张桌子

scores(user, score)

我有这个查询

SET @row_num = 0; 
SELECT @row_num := @row_num + 1 as row_index, user, score 
FROM scores ORDER BY score DESC

现在我想从这个查询结果中选择名称为“john”且得分为“1400”的用户,以了解他的 row_index 是什么,类似于

SELECT row_index 
FROM *result* WHERE user='john' AND score=1400

我怎么做?我试过

SET @row_num = 0; 
SELECT row_index 
FROM (SELECT @row_num := @row_num + 1 as row_index, user, score 
      FROM scores ORDER BY score DESC)      
WHERE user='john' AND score=1400`

但 phpMyAdmin 说

#1248 - Every derived table must have its own alias

我怎样才能做到这一点?

谢谢你,亚历山德罗

4

4 回答 4

2

您尚未向派生表添加别名。

SELECT row_index FROM (...) AS alias
WHERE alias.user = 'john' AND alias.score = 1400
于 2013-01-08T17:06:53.590 回答
2

询问:

SET @row_num = 0; 
SELECT a.row_index 
FROM (SELECT @row_num := @row_num + 1 as row_index, 
             user, 
             score 
             FROM scores ) a
WHERE a.user='john' AND a.score=1400
ORDER BY a.score DESC

我认为子查询中的排序并不总是允许的。

于 2013-01-08T17:10:51.660 回答
1

尝试使用视图

SET @row_num = 0; 
CREATE VIEW v AS SELECT @row_num := @row_num + 1 as row_index, user, score FROM scores ORDER BY score DESC;
SELECT row_index FROM v;
于 2013-01-08T17:10:51.497 回答
1

试试这个:

SET @row_num = 0; 

SELECT row_index FROM (SELECT @row_num := @row_num + 1 as row_index, user, 
score FROM scores ORDER BY score DESC) AS alias1 WHERE user='john' AND score=1400
于 2013-01-08T17:31:39.220 回答