Mysql – Select rows from table 1 only if all corresponding rows have certain status in the join table

join;MySQL

These are the tables

Orders

  • id
  • status

Order_lines

  • id
  • order_id

Invoice_lines

  • id
  • invoice_id
  • order_line_id

Invoices

  • id
  • status

I would like to retrieve only orders whose invoices are in approved or closed status. If any invoices are in open status, that order should not be selected

I tried this

 SELECT o.id FROM orders o INNER JOIN order_lines ol ON ol.orders_id = o.id 
                     INNER JOIN invoice_lines il ON il.order_line_id = ol.id 
                     INNER JOIN invoices i ON i.id = il.invoice_id 
                     AND i.status IN ('approved', 'closed')

I keep getting orders which have invoices in open state. This is not the result I want. I want orders for whose invoices are only in approved and closed status

Best Answer

There are a couple issues I'll have to gloss over at this point due to lack of info:

  • no DDL; no sample data; no list of valid invoices.status values
  • "invoices are only in approved and closed status" implies an invoice needs at least 2 records ... one with status='approved' and one with status='closed'

Instead of trying to find all orders with invoices that are a) 'approved' and 'closed', or b) 'approved' or 'closed' ... just look for orders that have no invoices with a status other than 'approved' or 'closed':

select distinct
       o.id
from   orders o
where not exists(select 1
                 from   order_lines ol
                 join   invoice_lines il
                 on     il.order_line_id = ol.id

                 join   invoices i
                 on     i.id = il.invoice_id
                 and    ifnull(i.status,'UNDEFINED') not in ('approved','closed')

                 where  ol.order_id = o.id)