使用SQL JOIN和COUNT

Lee*_*Lee 2 php mysql sql join

让两个表,一个持有用户信息,一个持有某种用户记录,比如收据.用户和收据之间存在一对多关系.

检索用户的最佳SQL方法是什么,按最大收据数排序?

我能想到的最好的方法是使用连接和计数(?)来返回用户数组及其相关收据的数量.

有没有办法在这个实例中使用count函数?

select * from `users` inner join `receipts` on `users`.`id` = `receipts`.`uId`
Run Code Online (Sandbox Code Playgroud)

Men*_*los 5

如果OP希望利用users表中的数据包含其他信息(其他聚合等...):

SELECT `users`.`id`,
       count(`receipts`.`uId`)
FROM `users`
INNER JOIN `receipts` ON `users`.`id` = `receipts`.`uId`
GROUP BY `users`.`id`
ORDER BY count(`receipts`.`uId`) DESC
Run Code Online (Sandbox Code Playgroud)

否则,只receipts需要表格......

SELECT `users`.`id`,
       count(`receipts`.`uId`)
FROM `receipts`
GROUP BY `receipts`.`uId`
ORDER BY count(`receipts`.`uId`) DESC
Run Code Online (Sandbox Code Playgroud)