SQL - 最大与内部连接

SQL - Max Vs Inner Join

我有一个问题,就速度而言,哪种方法更好。 我有一个包含 2 个表的数据库,如下所示:

表 2

UniqueID 价格

1 100
2 200
3 300
4 400
5 500

表 1

UniqueID 用户
1 汤姆
2 汤姆
3 杰瑞
4 杰瑞
5 杰瑞

我想获得每个用户的最高价格,我现在面临 2 个选择:

使用 Max 或使用下面建议的 Inner Join post:Getting max value from rows and joining to another table

哪种方法效率更高?

您的问题的答案是尝试这两种方法,看看哪种方法对您环境中的数据执行得更快。除非您有大量数据,否则差异可能并不重要。

在这种情况下,group by的传统方法可能更好:

select u.user, max(p.price)
from table1 u join
     table2 p
     on u.uniqueid = p.uniqueid
group by u.user;

对于这样的查询,您需要 table2(uniqueid, price) 上的索引,也许还需要 table1(uniqueid, user) 上的索引。这取决于数据库引擎。

我建议 not exists:

而不是 join
select u.user, p.price
from table1 u join
     table2 p
     on u.uniqueid = p.uniqueid
where not exists (select 1
                  from table1 u2 join
                       table2 p2
                       on u2.uniqueid = p2.uniqueid
                  where p2.price > p.price
                 );

请注意,这些并不完全做同样的事情。第一个 return 每个用户一行,无论如何。此版本可以 return 多行,如果有多行具有相同的价格。另一方面,它可以return行中最高价格的其他列,这很方便。

因为您的数据结构需要在子查询中使用 join,我认为您应该坚持使用 group by 方法。