MySQL 名称绑定?

MySQL name binding?

SELECT Score, (SELECT COUNT(*) FROM (SELECT DISTINCT Score FROM Scores WHERE Score >= s.Score) AS tmp) AS Rank
FROM Scores s
ORDER BY Score DESC

谁能告诉我为什么最里面的子查询不知道 s.score 列?

correlated subquery ("tmp") 嵌套太深,实际上 "tmp" 的细节不为外部查询所知:

SELECT
      Score
    , (
            SELECT
                  COUNT(*)
            FROM ( ------------------------------
                  SELECT DISTINCT
                        Score
                  FROM Scores
                  WHERE Score >= s.Score
            ) AS tmp ----------------------------
      )
      AS rank
FROM Scores s
ORDER BY
      Score DESC
;

您可以简单地使用 count(distinct score) 并删除不需要的图层。但是还要注意,必须非常精确地说明哪些列用于什么目的,因此请确保 在每个列引用 前加上 table 别名或 table name 如果没有定义别名。没有例外。

SELECT
      s.Score
    , (
            SELECT
                  COUNT(DISTINCT s2.Score)
            FROM Scores s2
            WHERE s2.Score >= s.Score
      )
      AS rank
FROM Scores s
ORDER BY
      s.Score DESC
;

ps:rank() 是一个函数名,所以我不太喜欢使用 "rank" 作为列名,因为它会让人感到困惑。

----

for MS SQL Server(抱歉,看错标签了,留给其他读者吧)

我鼓励避免在 select 子句中使用相关子查询,在 from clause 和 [=17] 中这样做效率更高=] 在 MS SQL 中可用 服务器非常适合:

SELECT
      s.Score
    , ca.[rank]
FROM Scores s
CROSS APPLY (
      SELECT
            COUNT(DISTINCT s2.Score) AS [rank]
      FROM Scores s2
      WHERE s2.Score >= s.Score
      ) ca
ORDER BY
      s.Score DESC
;