SQL: select all customers that have all items expired

Lunin Roman :

Consider the following DB structure

customer (id)
invoice (id, customer_id)
invoice_item (id, invoice_id, warranty_expiry)

I need to select all customers, where all their items are expired. Here is what I have so far

select * from customer c
inner join invoice i on c.id = i.customer_id
inner join invoice_item ii on i.id = ii.invoice_id
where ii.warranty_expiry < NOW()
group by c.id
having COUNT(ii.id) // <--- 

It feels like I should put something in HAVING clause, but I don't have an exact count of items for each client.

GMB :

You can indeed use a having clause to ensure that the given customer has all their items expired. This works by moving the check on warranty_expiry from the where clause to the having clause, as follows:

select c.id
from customer c
inner join invoice i on c.id = i.customer_id
inner join invoice_item ii on i.id = ii.invoice_id
group by c.id
having max(ii.warranty_expiry >= NOW()) = 0

Note that select * and group by do not go along well (although older versions of MySQL do allow it by default). You should enumerate the columns that you want to retain in the select clause and in the group by clause.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=5629&siteId=1