我接下来有两张桌子:
表格查询和表格时间:
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个最大文本?
答案 0 :(得分: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 ║
╚═════════╩══════╩═════╝