I have this query, but it takes too long, approximately 30 seconds via NaviCat. How can it be optimized if it's possible?
SELECT DISTINCT c.clientid, c.name, c.email, c.region
FROM clients c RIGHT JOIN orders o ON c.clientid = o.clientid
WHERE o.order_status = 'pending'
AND c.clientid NOT IN (
SELECT DISTINCT c.clientid
FROM clients c, orders o
WHERE c.clientid = o.clientid AND o.order_status = 'paid'
)
ORDER BY c.id DESC
To understand better what I need: I have 2 tables:
clients (id, clientid, name, email, region)
orders (id, orderid, clientid, order_amount, order_status, ….)
Example of records:
Client | Order | Status
-----------------------
C1 | O1 | (paid)
C1 | O2 | (pending)
C2 | O3 | (paid)
C3 | O4 | (pending)
C4 | O5 | (paid)
C5 | O6 | (pending)
I need to return only C3 and C5
Many thanks for your answers.
o.order_status =? Is every orders have one status ?RIGHT JOIN? It seems like you really want anINNER JOIN. (Actually it seems like you really want anINclause, but I can imagine performance reasons forcing you to use aJOINinstead.)idandclientidin tableclient)