WITH AS短语,也叫做子查询部分(subquery factoring),是用来定义一个SQL片断,该SQL片断会被整个SQL语句所用到。
WITH t AS ( SELECT user_id,SUM(grade_num) AS grade_sum FROM (SELECT user_id,grade_num * IF(type= ‘add‘,1,-1) AS grade_num FROM grade_info )AS t1 GROUP BY user_id ) SELECT id,name,grade_sum FROM t JOIN user u ON u.id = t.user_id WHERE grade_sum = (SELECT MAX(grade_sum) FROM t)