我将分 3 步解决这个问题。首先获取每个城市的每本书的数量。
select customers.city, books.title, count(books.title) as count
from loaned, books, customers
where loaned.userID = customers.userID
and loaned.bookID = books.bookID
group by customers.city, books.title
此查询将返回以下行。
+------------+-------------------------------+-------+
| city | title | count |
+------------+-------------------------------+-------+
| Harrogate | The cross rabbit | 1 |
| Harrogate | PHP and MySQL web development | 2 |
| Whitehaven | Greek Mythology | 1 |
| Whitehaven | Dino-soaring | 2 |
| Sale | Magic tricks | 3 |
| Sale | Dino-soaring | 2 |
+------------+-------------------------------+-------+
使用该数据,然后我将使用它对每个计数最多的城市进行分组。
select city, max(count) as count
from
(
select customers.city , books.title, count(books.title) as count
from loaned, books, customers
where loaned.userID = customers.userID
and loaned.bookID = books.bookID
group by customers.city, books.title
) as city_book_max_count
group by city
这将返回这些行,
+------------+-------+
| city | count |
+------------+-------+
| Harrogate | 2 |
| Whitehaven | 2 |
| Sale | 3 |
+------------+-------+
使用 2 个表中的数据,我们可以将它们连接到 city 和 count,以获取在两个表上匹配的相应书籍。
select city_book_count.city, city_book_count.title
from
(
select customers.city , books.title, count(books.title) as count
from loaned, books, customers
where loaned.userID = customers.userID
and loaned.bookID = books.bookID
group by customers.city, books.title
) as city_book_count
join
(
select city, max(count) as count
from
(
select customers.city , books.title, count(books.title) as count
from loaned, books, customers
where loaned.userID = customers.userID
and loaned.bookID = books.bookID
group by customers.city, books.title
) as city_book_count_temp
group by city
) as city_book_max_count
on city_book_count.city = city_book_max_count.city
and city_book_count.count = city_book_max_count.count