mysql order by不适用于group by

时间:2019-07-23 10:10:33

标签: mysql sql

当我通过按顺序使用group转换回而不对联接表进行排序时

select * from (select 
  sf.full_path, sf.folder_name, sf.server_id, p.folder_id, p.user_id, p.permission, u.username, p.id as perm_id
from shared_folders as sf  
inner join permissions as p on (p.folder_id = sf.id)  
inner join users as u on (u.id = p.user_id)  
where sf.server_id = 1 and u.username like "%srkgn%" 
order by p.id desc
) as a
group by folder_id, user_id

1 个答案:

答案 0 :(得分:0)

GROUP BYSELECT *只是没有多大意义。 SELECT正在选择不是聚合键的未聚合列。这些额外的列应该是聚合函数的参数。

如果要选择最后一条记录,则最好的方法是ROW_NUMBER()。但是,如果您的查询完全可行,我猜您正在使用旧版本的MySQL。

因此,请使用变量。这有点麻烦,但至少准确:

from (select a.*,
             (@rn := if(@fu = concat_ws(':', folder_id, p.user_id), @rn + 1,
                        if(@fu := concat_ws(':', folder_id, p.user_id), 1, 1)
                       )
             ) as rn
      from (select sf.full_path, sf.folder_name, sf.server_id, p.folder_id, p.user_id, p.permission, u.username, p.id as perm_id
            from shared_folders sf join
                 permissions p
                 on p.folder_id = sf.id join 
                 users u
                 on u.id = p.user_id  
                 where sf.server_id = 1 and
                       u.username like '%srkgn%;
            order by p.folder_id, p.user_id, p.id desc
           ) a cross join
           (select @fu := '', @rn := 0) params
      group by folder_id, user_id
     ) a
where rn = 1;