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
还是一个错误。请帮忙。感谢。
答案 0 :(得分:1)
由于您使用的是汇总MAX()
,因此您应该使用HAVING
子句而不是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
答案 1 :(得分: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
子句中的别名。此外,我在您的查询中添加了表别名,以使其更具可读性。