0

mysql 语句中 group by 的问题

 1 year ago
source link: https://www.v2ex.com/t/936176
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  MySQL

mysql 语句中 group by 的问题

  sniperking1234 · 17 小时 46 分钟前 · 1371 次点击

有个需求以用户为维度进行统计订单,并显示出用户相关信息,那么我写 sql 的时候,用下面哪种方式比较合适

第一种是把用户信息相关的字段放到 group by 中,在 select 中就也可以显示相应的字段,这样一个 sql 语句就可以查询出来统计信息和用户信息。

select count(userid), user_id ,user_name ,user_type ,user_level ...  from user group by user_id, user_name, user_type, user_level

第二种是先按照 user_id 进行聚合统计,然后再根据 userid 查表,补全用户信息,这样就需要查两次

select count(userid), user_id, ...  from ... group by user_id

select ... from ... where user_id in (...)

第一种方式明显是更简单的,但是把很多冗余的字段放到 group by 的条件中,会不会有性能问题,或者第一种写法可能会带来其他问题,求助下大家的意见,如果有更好的 sql 写法,也希望大家能够帮忙分享一下经验。

ps:无论第一种还是第二种,都需要联表查询


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK