0
SELECT product_key.contact_email, product_key.client_name, product_key.status, product_key.key, payment.paymentdate, product_key.id, MAX(paymentdate) AS latest_payment, DATE_ADD(MAX(paymentdate), INTERVAL 1 MONTH) AS expiration_date 
FROM product_key LEFT OUTER JOIN payment ON payment.keyid=product_key.id 
WHERE product_key.status = 'purchased' AND expiration_date = DATE_ADD(NOW(), INTERVAL 10 DAY) GROUP BY product_key.id 
ORDER BY client_name asc

这是我的查询。我知道我不能在 WHERE 子句中使用别名,因为在 SELECT 之前首先读取了 WHERE。但即使我使用这样的东西:

SELECT product_key.client_name, DATE_ADD(MAX(paymentdate), INTERVAL 1 MONTH) AS expiration_date 
FROM product_key LEFT OUTER JOIN payment ON payment.keyid=product_key.id 
WHERE DATE_ADD(MAX(paymentdate), INTERVAL 1 MONTH) = DATE_ADD(NOW(), INTERVAL 10 DAY) AND product_key.status = 'purchased' 
GROUP BY product_key.id 
ORDER BY client_name asc

还是一个错误。请帮忙。谢谢。

4

2 回答 2

1

由于您使用的是聚合MAX(),因此您应该使用 itHAVING子句而不是WHERE. 假设除了您的查询是正确且功能正常之外,您可以像这样重写它

SELECT product_key.client_name, 
       DATE_ADD(MAX(paymentdate), INTERVAL 1 MONTH) AS expiration_date 
  FROM product_key LEFT OUTER JOIN payment 
    ON payment.keyid=product_key.id 
   AND product_key.status = 'purchased' 
 GROUP BY product_key.id 
HAVING DATE_ADD(MAX(paymentdate), INTERVAL 1 MONTH) = DATE_ADD(NOW(), INTERVAL 10 DAY) 
 ORDER BY client_name

或者

SELECT product_key.client_name, 
       DATE_ADD(MAX(paymentdate), INTERVAL 1 MONTH) AS expiration_date 
  FROM product_key LEFT OUTER JOIN payment 
    ON payment.keyid=product_key.id 
   AND product_key.status = 'purchased' 
 GROUP BY product_key.id 
HAVING expiration_date = DATE_ADD(NOW(), INTERVAL 10 DAY) 
 ORDER BY client_name
于 2013-08-26T03:08:49.050 回答
1

您不能在select子句中使用该子句中定义的别名where。但这没关系,因为您想使用having子句:

SELECT pk.contact_email, pk.client_name, pk.status, pk.key, p.paymentdate, pk.id,
       MAX(paymentdate) AS latest_payment,
       DATE_ADD(MAX(paymentdate), INTERVAL 1 MONTH) AS expiration_date 
FROM product_key pk LEFT OUTER JOIN
     payment p
     ON p.keyid = pk.id 
WHERE pk.status = 'purchased'
GROUP BY pk.id 
HAVING expiration_date = DATE_ADD(NOW(), INTERVAL 10 DAY)
ORDER BY client_name asc;

可以having子句中使用别名。此外,我在您的查询中添加了表别名以使其更具可读性。

于 2013-08-26T03:14:38.197 回答