下表的结果是否有差异?

Is there any diff between the results of the following tables?

基本信息:Ollivander's Inventory from Hacker rank

有区别吗
SELECT code, power, MIN(coins_needed) AS coins_needed
FROM Wands
GROUP BY code, power

SELECT code, m.power, m.coins_needed
 FROM (SELECT code, power, MIN(coins_needed) AS coins_needed 
       FROM Wands
       GROUP BY code, power
      ) AS m JOIN 
      Wands AS w
     ON m.code = w.code AND m.power = w.power AND 
        m.coins_needed = w.coins_needed

以及为什么我们需要加入原始 table 本身才能得到正确的结果? 我尝试使用 w3schools 中的 Product table,它 returns 除了数据的顺序外,结果相同。

显然这两个查询 看起来 不同并且可能会生成不同的执行计划。这些查询也 不同。

最重要的区别是第一个查询 return 为数据库中 codepower 的每个唯一组合查询一行。

如果有两行具有相同的最小值,则第二个查询将 return 重复。换句话说,它return原始数据中所有每个code/power组合的硬币数量最少。

一个更细微的区别是 NULL 值的处理方式。第一个查询 returns NULLcodepower。第二个过滤掉 NULL 值。

如果 codepower 没有 NULL 值并且如果 coins_needed 在具有相同 codepower。但是,这些都是很大的假设,查询并不等同。

请注意,window 函数是编写第二个查询的更简单方法:

SELECT code, power, coins_needed
FROM (SELECT w.*,
             RANK() OVER (PARTITION BY code, power ORDER BY coins_needed) as seqnum
      FROM Wands w
     ) w
WHERE seqnum = 1;

好吧,这不是 100% 等效,因为它包括 codepowerNULL 个值。