gpt4 book ai didi

mysql - 为什么这个左连接只返回一条记录?

转载 作者:行者123 更新时间:2023-11-29 05:16:10 27 4
gpt4 key购买 nike

这是一个示例输入、SQL 和输出,想知道为什么只返回一行?我正在使用 MySQL/MySQL Workbench。

+----+-------+
| Id | Score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+

SELECT
score_primary.score, COUNT(DISTINCT score_higher.score) + 1 AS rank
FROM
TestRank score_primary
LEFT JOIN TestRank score_higher ON score_higher.score > score_primary.score

输出:

+-------+------+
| score | Rank |
+-------+------+
| 3.5 | 4 |
+-------+------+

顺便说一句,如果我为这个新的 SQL 语句添加 group by,我怎么知道是否首先执行了 (1) group by,然后在 group-by 结果上左连接,或者 (2) 左连接,然后 group-通过左侧连接结果?

SELECT
score_primary.score, COUNT(DISTINCT score_higher.score) + 1 AS rank
FROM
TestRank score_primary
LEFT JOIN TestRank score_higher ON score_higher.score > score_primary.score
GROUP BY score_primary.score

最佳答案

在没有GROUP BY 的情况下使用聚合函数(例如COUNT())将导致implicit GROUP BY将所有行分组为一行。

If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.

关于mysql - 为什么这个左连接只返回一条记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32451858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com