0

我有两张桌子,usernamescore。两者都使用user_id.

我想选择得分最高的前 5 个用户名。我正在尝试以下查询,但它不起作用:

SELECT `user_name`  
  FROM `username` 
 WHERE `user_id` = ( SELECT `u_id` 
                       FROM `score` 
                       ORDER BY `high_score` DESC 
                       LIMIT 5 )

运行上述查询时出现此错误:#1242 - Subquery returns more than 1 row

4

2 回答 2

5

在您的WHERE条款中,您试图断言一个值(左侧)与值列表(右侧)的一致性或相等性。

使用IN运算符来实现这一点,因为它将左值与任何右值进行比较。

以下是您更正的代码。

SELECT    `user_name`
    FROM  `username`
    WHERE `user_id` IN(
              SELECT        `u_id`
                  FROM      `score`
                  ORDER BY  `high_score` DESC
                  LIMIT 5
              );

作为一种风格,使用连接更清晰、更优雅,尤其是对于像这样的简单查询。

SELECT        `u`.`user_name`
    FROM      `username` AS `u`
    INNER JOIN `score` AS `s`
        ON     `u`.`user_id` = `s`.`u_id`
    ORDER BY  `s`.`high_score` DESC
    LIMIT      5;
于 2012-07-01T22:08:54.007 回答
5

尝试这个:

SELECT `user_name`  
FROM `username`,`score` 
WHERE `user_id` = `u_id` 
ORDER BY `high_score` DESC 
LIMIT 5 
于 2012-07-01T22:12:55.420 回答