MySQL将子查询与FROM

时间:2016-04-27 18:55:01

标签: mysql correlated-subquery

我正在与Sakila sample database合作,并尝试获得每个国家/地区观看次数最多的电影。到目前为止,我已成功获得某个国家/地区观看次数最多的电影,其中包含以下查询的ID:

SELECT 
    F.title, CO.country, count(F.film_id) as times
FROM 
    customer C 
INNER JOIN 
    address A ON C.address_id = A.address_id
INNER JOIN 
    city CI ON A.city_id = CI.city_id
INNER JOIN 
    country CO ON CI.country_id = CO.country_id
INNER JOIN 
    rental R ON C.customer_id = R.customer_id
INNER JOIN 
    inventory I ON R.inventory_id = I.inventory_id
INNER JOIN 
    film F ON I.film_id = F.film_id
WHERE 
    CO.country_id = 1
GROUP BY 
    F.film_id
ORDER BY 
    times DESC
LIMIT 1;

我认为我必须在另一个查询的FORM中使用此查询或类似内容,但我已经尝试了所有我能想到的内容并且完全无法弄清楚如何执行此操作。

提前致谢!

1 个答案:

答案 0 :(得分:2)

我承认,这是一个很糟糕的问题。但是,只要它有效。

说明:

  • 子查询:几乎与您已有的相同。没有WHERELIMIT。导致每个国家的电影计数列表
  • 结果,按国家/地区分组
  • GROUP_CONCAT(title ORDER BY times DESC SEPARATOR '|||'),将在该“行”中提供所有标题,并且首先查看最多的标题。分隔符无关紧要,只要您确定它永远不会出现在标题中。
  • SUBSTRING_INDEX('...', '|||', 1)会生成字符串的第一部分,直到找到|||,在这种情况下是第一个(因此也是最常见的)标题

完整查询:

SELECT
    country_name,
    SUBSTRING_INDEX(
        GROUP_CONCAT(title ORDER BY times DESC SEPARATOR '|||'), 
        '|||', 1
    ) as title,
    MAX(times)
FROM (
    SELECT 
        F.title AS title, 
        CO.country_id AS country_id,
        CO.country AS country_name, 
        count(F.film_id) as times
    FROM customer C INNER JOIN address A ON C.address_id = A.address_id
    INNER JOIN city CI ON A.city_id = CI.city_id
    INNER JOIN country CO ON CI.country_id = CO.country_id
    INNER JOIN rental R ON C.customer_id = R.customer_id
    INNER JOIN inventory I ON R.inventory_id = I.inventory_id
    INNER JOIN film F ON I.film_id = F.film_id
    GROUP BY F.film_id, CO.country_id
) AS count_per_movie_per_country
GROUP BY country_id

概念证明(只要子查询是正确的):SQLFiddle