mysql - : HAVING c2. hacker_id <> c.hacker.id 这行的含义是什么?

标签 mysql sql

我一直在研究 HackerRank SQL 问题,"Challenges"

这就是问题:

Julia asked her students to create some coding challenges. Write a query to print the hacker_id, name, and the total number of challenges created by each student. Sort your results by the total number of challenges in descending order. If more than one student created the same number of challenges, then sort the result by hacker_id. If more than one student created the same number of challenges and the count is less than the maximum number of challenges created, then exclude those students from the result.

这个问题难倒了我,我在网上搜索看看其他人是如何解决的,当我遇到这个Github here时,他提出了一个非常优雅的解决方案。

SELECT c.hacker_id, 
       h.name, 
       COUNT(c.challenge_id) AS cnt 

FROM Hackers AS h 
   JOIN Challenges AS c ON h.hacker_id = c.hacker_id

GROUP BY c.hacker_id, h.name 
HAVING cnt = (SELECT COUNT(c1.challenge_id) 
              FROM Challenges AS c1 
              GROUP BY c1.hacker_id 
              ORDER BY COUNT(*) DESC 
              LIMIT 1) 
OR
       cnt NOT IN (SELECT COUNT(c2.challenge_id) 
       FROM Challenges AS c2 
       GROUP BY c2.hacker_id 
       HAVING c2.hacker_id <> c.hacker_id)

ORDER BY cnt DESC, c.hacker_id;

我明白海报如何确保我们在 HAVING 的第一个条件下只能获得最大数量的挑战,但至于第二部分,我不太明白。我不确定为什么 HAVING 查询的第二个条件有效:HAVING c2.hacker_id <> c.hacker_id

c2.hacker_id 不会总是 = c.hacker_id 吗?

最佳答案

如果您对它们进行均衡 (c2.hacker_id = c.hacker_id),则结果与相同的 hacker_id 相关。在不等式条件下,它通过不包括 hacker_id 本身进行计数。这意味着计算 hacker_id 不等于外部查询的 hacker_id 的挑战数量,并将这些计数从主查询中排除。

关于mysql - : HAVING c2. hacker_id <> c.hacker.id 这行的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54857386/

相关文章:

mysql - SQL RAND查询选择所有记录并且不使用联接表

php - XAMPP,PHP : echo adds two spaces to blob read from database

php - 安卓连接错误: Gralloc pipe failed

mysql - 同时为许多表创建列并从表名填充它_MYSQL

sql查询累加值计算

c# - 为什么我应该为具体的 DataProvider 类创建接口(interface)

php - 快速生成随机 MySQL 行并多次运行相同的 sql 查询

php - stdClass 与数组。推荐哪个?

php - 我可以独立使用 Laravel 的数据库层吗?

php - 多个表的外键