一般执行顺序
- from =》 判断从哪些表取数据
- ON =》 临时表条件(虚拟表)
- JOIN =》 连接多表
- where =》判定条件,得出结果集
- group by=》对结果集分组
- having =》 对结果集过滤
- select =》 查询字段(这里可再进行聚合函数)
- DISTINCT =》 唯一筛选
- order by =》排序
- limit =》限定条数
查询拍卖出价表中,每个用户最高出价。(一个表中用户多次出价, 只取出每个用户记录最高的一条)
解题思路:首先必须要max(price),取得最大值。但在此之前要分组,按照用户ID进行分组。
如果没有 group by,只使用 max 的时候如下:
select max(price) max_price,uid from paimai_order_record;
上面只有最高的一条,而在 表名后添加 group by uid 反而变成多条了。
select max(price) max_price,uid from paimai_order_record group by uid;
另外 limit n,m 的方式中效率是非常低的,这时可以通过在 where 中增加条件,从而提高效率。
例如在ID连续的情况下:
select * from t_user where id between 9000000 and 9000100 limit 100;
如果ID不连续,但一般至少也是递增的,通过子查询查出最小 ID,然后限定为 > min_id,然后再 limit 查询数量,例如:
select * from user where type = 8 and id >= (
select id from user where type = 8 limit 100000,1
) limit 100;