mysql - 从结果中选择

时间:2013-01-08 17:05:26

标签: mysql select phpmyadmin

我有一张桌子

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

我该怎么做?

谢谢你, 的Alessandro

4 个答案:

答案 0 :(得分:2)

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

SELECT row_index FROM (...) AS alias
WHERE alias.user = 'john' AND alias.score = 1400

答案 1 :(得分: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

我认为不总是允许在Subquery中订购。

答案 2 :(得分:1)

尝试使用views

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;

答案 3 :(得分: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