My tables, borrower:
+----------+---------+
| name | loan_id |
+----------+---------+
| Adams | L16 |
| Curry | L93 |
| Hayes | L15 |
| Jackson | L14 |
| Jones | L17 |
| Smith | L11 |
| Smith | L23 |
| Williams | L17 |
+----------+---------+
loan:
+---------+-------------+--------+
| loan_id | branch_name | amount |
+---------+-------------+--------+
| L11 | Round Hill | 900 |
| L14 | Downtown | 1500 |
| L15 | Perryridge | 1500 |
| L16 | Perryridge | 1300 |
| L17 | Downtown | 1000 |
| L23 | Redwood | 2000 |
| L93 | Mianus | 500 |
+---------+-------------+--------+
I wish to find the maximum loan taken by the customer.
I was partially successful with the query:
select name, max(amount)
from loan, borrower
where borrower.loan_id=loan.loan_id;
Result:
+-------+-------------+
| name | max(amount) |
+-------+-------------+
| Adams | 2000 |
+-------+-------------+
But it is taking the name from the first row and finding the maximum amount and printing the result. So I used the having
clause like this:
select name, amount
from loan, borrower
where borrower.loan_id=loan.loan_id
having max(amount)=amount;
But I get an empty set.
You can
group by
customer and get themax
amount from the joinedloan
table.This query is very similar to your first attempt, but the difference is in the
group by
clause. This causes the query to return one row per customer name (name is in group by). Themax
(andsum
too, in my example) are calculated per 'group', so per name in this case.In your query, you didn't have
group by
, so themax
is determined (aggregated) over all rows. Many other databases wouldn't even execute your query, because they feel a field should either be specified ingroup by
or it should be called in an aggregation function likemin
,max
, orsum
. MySQL is a bitsillydifferent, because it just picks any of the customer names to display.Of course, it would be better if a customer also has an ID. After all, you're likely to get two customers both named Smith.