我有两个相关的表格:
(1)人包含姓名和图片文件。
(2)城市包含他们访问过的城市。
人
id name image
1 John NULL
2 Carrie 001.jpg
3 Desmond 002.jpg
4 Harry 003.jpg
5 Paul NULL
城市
id city people_id year_visited
1 Chicago 1 2000
2 Chicago 4 2000
3 Chicago 5 2001
4 Paris 1 2000
5 Paris 2 2002
6 Chicago 4 2002
7 Chicago 1 2001
8 London 1 2004
9 Sydney 5 2001
10 Sydney 1 2002
11 Rio 5 2002
12 London 5 2004
13 Sydney 5 2003
14 Sydney 5 2005
我想确定所有没有图片的人,以及他们访问过的城市。所以我要找的结果是:
name most_visited_city number_of_visits
John Chicago 2
Paul Sydney 3
我可以对他们访问过的城市进行group_concat,但不能深入到他们访问过的单个城市。
感谢所有人的帮助。
答案 0 :(得分:0)
以下内容包括人,城市和点数:
npm run build.dev -- --debug
获取有关访问量最大的信息在MySQL中很棘手。如果数据不是太大,这是一种有效的方法:
select p.id, c.city, count(*) as cnt
from people p join
cities c
on p.id = c.people_id
where p.image is null
group by p.id, c.city;
答案 1 :(得分:0)
此查询应返回people_id
中每个cities
的访问量最大的城市。
SELECT t1.people_id, t2.city, t2.visits
FROM (
SELECT people_id, MAX(visits) AS max_visits
FROM (
SELECT people_id, city, COUNT(*) AS visits
FROM cities
GROUP BY people_id, city) x
GROUP BY people_id) AS t1
JOIN (
SELECT people_id, city, COUNT(*) AS visits
FROM cities
GROUP BY people_id, city) AS t2
ON t1.people_id = t2.people_id AND t1.max_visits = t2.visits
一般结构基于SQL Select only rows with Max Value on a Column中的答案,但不是获取表格中列的最大值,而是使用子查询中的最大值来计算每个城市的访问次数。不幸的是,它会导致一个丑陋的查询,因为你必须重复那个子查询,因为MySQL没有CTE。
然后,您可以将其与people
一起加入,以获取此人的姓名并过滤掉带有图片的人。
SELECT p.name, t2.city, t2.visits
FROM (
SELECT people_id, MAX(visits) AS max_visits
FROM (
SELECT people_id, city, COUNT(*) AS visits
GROUP BY people_id, city) x
GROUP BY people_id) AS t1
JOIN (
SELECT people_id, city, COUNT(*) AS visits
GROUP BY people_id, city) AS t2
ON t1.people_id = t2.people_id AND t1.max_visits = t2.max_visits
JOIN people AS p ON p.id = t1.people_id
WHERE p.image IS NULL