2016-09-29 37 views
0

我想獲得最近9個月沒有購買但在9-18個月前購買的客戶名單。 下面的查詢在本地主機上正常工作,但在具有MariaDB的服務器上無法正常工作。 SELECT MAX(o.date_modified) GROUP BY o.email是在服務器上導致錯誤的查詢。開放式購物車 - 在客戶名單上的MySQL查詢

是否有人可以重寫可以在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 

回答

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也不需要子查詢。

0

您需要correlatesub-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 
+0

謝謝,但它採取無盡的處理時間:( – user3282626

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工作臺發現組之前錯誤BY

+0

感謝您嘗試,但它不適用於我。 – user3282626