如何通过MySQL中的其他表计数和排序?

时间:2017-06-30 07:52:34

标签: mysql

我有两张桌子:

CREATE TABLE `apps` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    PRIMARY KEY (`id`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;

CREATE TABLE `downloads_stats` (
    `app_id` INT(10) UNSIGNED NOT NULL,
    `date` DATE NOT NULL,
    `downloads` INT(10) UNSIGNED NOT NULL,
    PRIMARY KEY (`app_id`, `date`),
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB

首先是我的应用列表,其他存储每个应用的下载编号。获得10个下载量最多的应用程序的最佳方法是什么?我可以做简单JOIN然后SUMORDER BY,但这是最有效的方法吗?

2 个答案:

答案 0 :(得分:0)

是的,我将LEFT JOINGROUP BY一起使用,例如:

SELECT a.id, a.name, SUM(ds.downloads) AS 'downloads'
FROM apps a LEFT JOIN downloads_stats ds ON a.id = ds.app_id
GROUP BY a.id, a.name
ORDER BY SUM(ds.downloads) DESC
LIMIT 10;

如果您只想要app_id,则不需要JOIN,例如:

SELECT app_id, SUM(downloads) as 'downloaded'
FROM downloads_stats
GROUP BY app_id
ORDER BY SUM(downloads) DESC

答案 1 :(得分:0)

是的,您可以将 android:gravity="center" LEFT JOIN

一起使用
GROUP BY