Вопрос

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):

select b.buyer_id
from bought b join
     house h
     on b.code = h.code
group by b.buyer_id
having min(h.owner_id) = max(h.owner_id);

The answer to the second question is similar. However, the focus is on owners rather than buyers.

select min(b.buyer_id)
from bought b join
     house h
     on b.code = h.code
group by h.owner_id
having min(b.buyer_id) = max(b.buyer_id);

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 each owner_id. The having clause then adds the condition that the query only returns the owner id when the minimum buyer and the maximum buyer are the same -- meaning there is only one value. You can also express this condition as count(distinct buyer_id) = 1, but min() and max() generally perform a bit better than count(distinct).

The select clause then returns those buyers. You could also include the owner to see whose house(s) they bought.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top