I have a query that I’m trying to clean up:
My original query is as follows:
SELECT h.userid, c.firstname, c.lastname, h.domain, h.nextduedate, h.domainstatus,
(SELECT COUNT(status)
FROM tblinvoices i, tblinvoiceitems ii
WHERE i.userid =h.userid
AND i.id = ii.invoiceid
AND i.STATUS LIKE 'Unpaid'
AND i.TOTAL = 80
AND ii.description LIKE 'Hosted Domain%')
AS invoice_count
FROM tblclients c, tblhosting h
WHERE h.userid=c.id AND c.status='Active'
AND c.id NOT IN (1,2,3,4,5)
AND h.domain LIKE '%thisdomain.com'
AND h.nextduedate<='2012-06-06'
ORDER BY h.domainstatus, h.nextduedate DESC
It works fairly well, but it isn’t 100% accurate. I’m getting all of the users with a “nextduedate” that is older than today’s date, but, there are some users with Unpaid invoices with a NULL nextduedate (account is cancelled, but they still have unpaid invoices).
This query gives me 22 users, but if I run:
SELECT DISTINCT i.userid, COUNT(i.status)
FROM tblinvoices i, tblinvoiceitems ii
WHERE i.id = ii.invoiceid
AND i.STATUS LIKE 'Unpaid'
AND i.TOTAL = 80
AND ii.description LIKE 'Hosted Domain%')
Then I get 26 users (and about 8 missing invoices).
The Next Due Date is really to show how late they are, the main focus of this query is to show all of the users with Unpaid invoices. I tried to combined the second query with the first one several different ways, but I can’t figure it out, and I think I locked up my server.
Ideally my return row would look like this:
userid, firstname, lastname, domain, domainstatus, “duedate” (this would ideally be the date of the oldest invoice, I’m using nextduedate because it’s easy), invoicecount (the number of unpaid invoices)
FYI, the invoice date is in i.invoicedate
I would greatly appreciate help figuring out how to optimize this query!
You may try to replace
DISTINCTwithGROUP BY