每个GROUP BY的MySQL n结果,按计数排序

时间:2017-09-22 08:51:26

标签: mysql sql laravel

MySQL n results per GROUP BY, Order by count

- Country有一个1-n的关系。

Company - Company有n-n关系。

我需要从每个区域设置中根据各自区域设置中的计数降序来获取Dishes,每个区域设置都有100个结果。

到目前为止我已经

Dish

示例数据:

enter image description here

期望的输出:

enter image description here

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

尝试使用子请求...

您的要求:

SELECT
    dishes.title,
    dishes.name,
    dishes.id,
    countries.locale,
    countries_count.dishes_nb
FROM countries 
    JOIN companies ON companies.`country_id` = countries.`id`
        JOIN company_dish ON company_dish.`company_id` = companies.`id`
            JOIN dishes ON company_dish.`dish_id` = dishes.`id`
    JOIN
        ({SubRequest}) countries_count ON countries_count.`country_id` = countries.`id`
ORDER BY
    countries_count.dishes_nb DESC

和子请求,按国家统计菜肴:

SELECT
    countries.id AS country_id,
    COUNT(company_dish.dish_id) AS country_dishes_nb
FROM countries 
    JOIN companies ON companies.country_id = countries.id
        JOIN company_dish ON company_dish.company_id = companies.id
GROUP BY
    country_id

或按国家/地区计算每道菜:

您的要求:

SELECT
    dishes.title,
    dishes.name,
    dishes.id,
    countries.locale,
    countries_count.dishes_nb
FROM countries 
    JOIN companies ON companies.`country_id` = countries.`id`
        JOIN company_dish ON company_dish.`company_id` = companies.`id`
            JOIN dishes ON company_dish.`dish_id` = dishes.`id`
    JOIN
        ({SubRequest}) countries_count ON countries_count.`country_id` = countries.`id`
        AND countries_count.`dish_id` = dishes.`id`
ORDER BY
    countries_count.dishes_nb DESC

和子请求:

SELECT
    countries.id AS country_id,
    dishes.id AS dish_id,
    COUNT(company_dish.dish_id) AS country_dishes_nb
FROM countries 
    JOIN companies ON companies.country_id = countries.id
        JOIN company_dish ON company_dish.company_id = companies.id
            JOIN dishes ON company_dish.dish_id = dishes.id) AS countries_count ON countries_count.country_id` = countries.`id`
GROUP BY
    country_id, dish_id

在{SubRequest}

中连接(替换)