3

我有接下来的 2 张桌子:

表查询和表时间:

id | text     id | mid | country
1    hello     1    1       UK
2     hi       2    1       PL
3     sd       3    2       USA

id = mid,国家不同(英国、美国等)。

我需要列出下一个清单:

UK - text 30 rows (this text has most mid in table 2 for UK)
USA - text 25 rows
PL - text 10 rows
...
SS - text 1 rows.

现在我有下一个想法:获取每个国家/地区的哪个 MID 具有最大行并通过 mid=id 获取文本并对其进行排序。

SELECT time.country,querys.text,COUNT(mid) AS cnt 
     FROM time INNER JOIN `querys` ON(time.mid = querys.id) 
      GROUP BY mid 
      ORDER BY country,cnt
      DESC

但是使用此代码,我会收到所有带有计数的文本。如

UK text1 30, 
UK text2 25, 
PL text2 10, 
PL text3 5 ..

但是我每个国家只需要一个最大值,任何人都可以帮助如何将每个国家的查询减少到 1 个最大文本?

4

1 回答 1

2
SELECT  a.country, 
        b.text, 
        COUNT(*) AS cnt 
FROM    time a
        INNER JOIN querys b
            ON a.mid = b.id
        INNER JOIN
        (
            SELECT  Country, 
                    MAX(totalCount) max_count
            FROM
                    (
                        SELECT  Country, Mid, 
                        COUNT(*) totalCount
                        FROM    time
                        GROUP   BY Country, Mid
                    ) s
            GROUP   BY Country
        ) c ON a.country = c.country
GROUP   BY a.country, b.text, c.max_count
HAVING  COUNT(*) = c.max_count
ORDER   BY cnt DESC

输出

╔═════════╦══════╦═════╗
║ COUNTRY ║ TEXT ║ CNT ║
╠═════════╬══════╬═════╣
║ UA      ║ sdf  ║  10 ║
║ USA     ║ qw   ║   2 ║
╚═════════╩══════╩═════╝
于 2013-05-11T15:33:04.640 回答