Doing a COUNT in MySQL
I have the following two tables -- userprofile and videoinfo. videoInfo has a FK to userprofile.
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,
`uploa开发者_Python百科ded_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`)
)
What is the SQL statement I would use to show the count of videos each userprofile has and order by COUNT?
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
SELECT uploaded_by_id, COUNT(ID) as cnt
FROM userprofile_videoinfo
GROUP BY uploaded_by_id
ORDER BY cnt DESC;
精彩评论