0

我有一个要清理的查询:

我的原始查询如下:

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

它工作得相当好,但它不是100%准确的。我让所有用户的“nextduedate”早于今天的日期,但是,有些用户的未付发票的 nextduedate 为 NULL(帐户已取消,但他们仍有未付发票)。

这个查询给了我 22 个用户,但是如果我运行:

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%')

然后我得到了 26 个用户(以及大约 8 个丢失的发票)。

下一个到期日期实际上是显示他们有多晚,此查询的主要重点是显示所有未付发票的用户。我试图以几种不同的方式将第二个查询与第一个查询结合起来,但我无法弄清楚,我想我锁定了我的服务器。

理想情况下,我的返回行如下所示:

userid、firstname、lastname、domain、domainstatus、“duedate”(理想情况下,这将是最旧发票的日期,我使用 nextduedate 因为它很简单)、invoicecount(未付发票的数量)

仅供参考,发票日期在 i.invoicedate

我将非常感谢帮助弄清楚如何优化此查询!

4

1 回答 1

1

您可以尝试替换DISTINCTGROUP BY

SELECT h.userid, c.firstname, c.lastname, h.domain, h.nextduedate, h.domainstatus, count(i.status) AS invoice_count

FROM tblclients c, tblhosting h 
LEFT JOIN tblinvoices i ON i.userid =h.userid         
    AND i.STATUS LIKE  'Unpaid'
    AND i.TOTAL = 80
LEFT JOIN tblinvoiceitems ii ON i.id = ii.invoiceid
    AND ii.description LIKE  'Hosted Domain%'


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'
GROUP BY h.userid 
ORDER BY h.domainstatus, h.nextduedate DESC
于 2012-06-06T07:38:17.887 回答