在MySQL中执行COUNT

时间:2011-07-04 20:07:40

标签: mysql sql join aggregate-functions

我有以下两个表 - userprofile和videoinfo。 videoInfo有一个FK到用户配置文件。

CREATE TABLE `userprofile_userprofile` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `full_name` varchar(100) NOT NULL,
   ...
 )

CREATE TABLE `userprofile_videoinfo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(256) NOT NULL,
  `uploaded_by_id` int(11) NOT NULL,
  ...
  KEY `userprofile_videoinfo_e43a31e7` (`uploaded_by_id`),
  CONSTRAINT `uploaded_by_id_refs_id_492ba9396be0968c` FOREIGN KEY (`uploaded_by_id`) REFERENCES `userprofile_userprofile` (`id`)
)

我会使用什么SQL语句来显示每个用户配置文件的视频数量并按COUNT排序?

2 个答案:

答案 0 :(得分:4)

SELECT u.id as userId, count(v.uploaded_by_id) as videosCount
FROM userprofile_userprofile u
    LEFT OUTER JOIN userprofile_videoinfo v
        ON v.uploaded_by_id = u.id
GROUP BY u.id
ORDER BY count(v.uploaded_by_id) DESC

答案 1 :(得分:0)

SELECT uploaded_by_id, COUNT(ID) as cnt
FROM userprofile_videoinfo
GROUP BY uploaded_by_id
ORDER BY cnt DESC;