打开购物车 - 客户列表上的MySQL查询

时间:2016-09-29 17:13:21

标签: php mysql sql group-by mariadb

我正在尝试获取在过去9个月内没有购买但在9-18个月之前购买的客户列表。 以下查询在localhost上正常工作,但在具有MariaDB的服务器上没有。 SELECT MAX(o.date_modified) GROUP BY o.email是导致服务器上的错误的查询。

任何人都可以重写可以在MariaDB上运行的语句。我的问题是

SELECT 
o.firstname AS FirstName, 
o.lastname AS LastName,  
o.date_modified AS OrderDate, 
o.order_id AS OrderID, 
op.name AS ProductName, 
op.model AS ProductModel, 
p.sku AS ProductSKU 

FROM `store_order` AS o 
JOIN `store_order_product` op 
    ON o.order_id=op.order_id 
JOIN `store_product` AS p 
    ON op.product_id = p.product_id 

WHERE o.order_status_id = '3' 
AND TIMESTAMPDIFF( MONTH , (SELECT MAX(o.date_modified) GROUP BY o.email), CURDATE( ) ) 
BETWEEN 9 AND 18 
ORDER BY o.date_modified DESC

3 个答案:

答案 0 :(得分:0)

您需要correlate sub-query

SELECT o.firstname AS FirstName 
       .......
FROM   store_order AS o 
       JOIN store_order_productop 
         ON o.order_id = op.order_id 
       JOIN store_productas p 
         ON op.product_id = p.product_id 
WHERE  o.order_status_id = '3' 
       AND Timestampdiff(month, (SELECT Max(o1.date_modified) 
                                 FROM   store_order o1 
                                 WHERE  o1.email = o.email), Curdate()) BETWEEN 9 AND 18 
ORDER  BY o.date_modified DESC 

答案 1 :(得分:0)

这对我有用

SELECT 
o.firstname AS FirstName, 
o.lastname AS LastName,  
o.date_modified AS OrderDate, 
o.order_id AS OrderID, 
op.name AS ProductName, 
op.model AS ProductModel, 
p.sku AS ProductSKU 

FROM `store_order` AS o 
JOIN `store_order_product` op 
    ON o.order_id=op.order_id 
JOIN `store_product` AS p 
    ON op.product_id = p.product_id 

WHERE o.order_status_id = '3' 
AND TIMESTAMPDIFF( MONTH , (SELECT MAX(o.date_modified) FROM `store_order` GROUP BY o.email), CURDATE() ) 
BETWEEN 9 AND 18 
ORDER BY o.date_modified DESC

MySQL Workbench在GROUP BY

之前发现错误

答案 2 :(得分:0)

SELECT ...
    GROUP BY email
    HAVING MAX(date_modified) > NOW() - 18 MONTH  -- bought in last 18 months
       AND MAX(date_modified) < NOW() -  9 MONTH  -- but not in the last 9

也就是说,不需要JOIN或子查询。