I have 3 tables.
Owner(owner_id, name)
House(code, owner_id, price)
Buyer(buyer_id, name)
Bought(buyer_id, code, price_bought, date_bought)
I have the following query:
List the names of the buyers that bought all the houses from some owner?
I know how to find if someone bought all the houses from a particular owner (say owner with id = 1):
SELECT name
FROM buyer
WHERE NOT EXISTS (SELECT code
FROM house
WHERE owner_id = 1
AND code NOT IN (SELECT code
FROM bought
WHERE bought.buyer_id= buyer.buyer_id))
How can I make this work for all owners?
The sentence: "List the names of the buyers that bought all the houses from some owner?". This can be interpreted two ways. (1) All the houses the buyer bought are from one owner. Or (2) All the houses sold by one owner when to the same buyer.
The following answers (1):
The answer to the second question is similar. However, the focus is on owners rather than buyers.
EDIT:
In both cases, the logic is quite similar, but let's look at the second query. The join is just combining the buyer and owner ids together (not really interesting).
The
group by
is creating a single row for eachowner_id
. Thehaving
clause then adds the condition that the query only returns theowner
id when the minimum buyer and the maximum buyer are the same -- meaning there is only one value. You can also express this condition ascount(distinct buyer_id) = 1
, butmin()
andmax()
generally perform a bit better thancount(distinct)
.The
select
clause then returns those buyers. You could also include theowner
to see whose house(s) they bought.