使用默认值优化多个表的查询

时间:2013-09-16 20:10:55

标签: php mysql sql oscommerce

我正在尝试使用Recover Cart Sales贡献在旧的osCommerce网站上优化一些非常慢的查询。

我正在尝试从购物车和客户表中提取信息(我可以轻松完成)。诀窍在于我需要弄清楚它们最后一次联系的时间(无需进行其他查询)。这存在于另一个表中,如果我们之前从未联系过它们,那么表中就没有任何东西,所以它应该是null。

这就是我所拥有的,除了scart表中的条目外,它只会提取数据。

SELECT DISTINCT cb.customers_id, c.customers_firstname, c.customers_lastname, c.customers_email_address, sc.datemodified AS last_contacted
    FROM customers_basket cb, customers c, scart sc
        WHERE c.customers_id = cb.customers_id
            AND cb.customers_id = sc.customers_id 
            AND cb.customers_basket_date_added < 20130916 
            AND cb.customers_basket_date_added > 20130101
        AND cb.customers_id NOT IN(SELECT sc.customers_id  //Excludes people we've contacted in the last month
                                FROM scart sc
                        WHERE sc.datemodified >20130816)
    ORDER BY cb.customers_id DESC

1 个答案:

答案 0 :(得分:1)

听起来你需要LEFT JOIN?如果存在,它将返回您感兴趣的行,如果不存在则返回NULL。

SELECT DISTINCT cb.customers_id, c.customers_firstname, c.customers_lastname, c.customers_email_address, sc.datemodified AS last_contacted
FROM customers_basket cb 
INNER JOIN customers c ON c.customers_id = cb.customers_id
LEFT JOIN scart sc ON cb.customers_id = sc.customers_id
WHERE cb.customers_basket_date_added < 20130916 
  AND cb.customers_basket_date_added > 20130101
  AND cb.customers_id NOT IN(SELECT sc.customers_id  //Excludes people we've contacted in the last month
                            FROM scart sc
                    WHERE sc.datemodified >20130816)
ORDER BY cb.customers_id DESC