我有一个查询,我正在尝试清理:
我的原始查询如下:
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%准确。我为所有用户提供了&#34; nextduedate&#34;这是比今天更早的日期,但是,有些用户的未付款发票中包含NULL nextduedate(帐户已取消,但他们仍有未付款的发票)。
这个查询给了我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,&#34; duedate&#34; (理想情况下,这是最早发票的日期,我使用nextduedate,因为它很简单),invoicecount(未付发票的数量)
仅供参考,发票日期为i.invoicedate
我非常感谢帮助弄清楚如何优化此查询!
答案 0 :(得分:1)
您可以尝试将DISTINCT
替换为GROUP 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