MySQL基于日期范围加入

时间:2012-12-02 09:35:12

标签: mysql

我正在创建一个用于测试脚本的模拟电子商务数据库;我想运行以下代码,但还包括根据到期日期选择卡片的进一步声明。

SELECT customerCard.cardNumber, customer.firstName, customer.eMailAddress, customer.lastName, cardType, expiryDate
FROM customerCard
LEFT JOIN customer
USING ( eMailAddress ) 
LEFT JOIN card
USING ( cardNumber )
WHERE card.Expiry =< DATE_FORMAT(NOW(),'%m-%Y')
ORDER BY  `customerCard`.`cardNumber` ASC

我在WHERE语句的行上出错 - 我该如何解决这个问题?什么是正确的语法?

2 个答案:

答案 0 :(得分:1)

请尝试以下操作:由于未提供表格架构/样本数据,因此代码主要基于假设。例如您的到期日期类似于'mm-yyyy' format

SELECT customerCard.cardNumber, customer.firstName, 
customer.eMailAddress, customer.lastName, cardType, expiryDate
FROM customerCard CC
LEFT JOIN customer CO
ON CC.eMailAddress = CO.eMailAddress 
LEFT JOIN card CD
ON CO.cardNumber = CD.cardNumber
WHERE DATE_FORMAT(CD.Expiry,'%m-%Y') =< DATE_FORMAT(NOW(),'%m-%Y') -- put both in same format
ORDER BY  CC.cardNumber ASC

答案 1 :(得分:0)

我已经从上面的帮助中找到了正确的MySQL查询语句。

SELECT customerCard.cardNumber, customer.firstName, customer.eMailAddress, customer.lastName, cardType, expiryDate
FROM customerCard
LEFT JOIN customer
USING ( eMailAddress ) 
LEFT JOIN card
USING ( cardNumber ) 
WHERE DATE_FORMAT( card.expiryDate,  '%y-%m-%d' ) <= DATE_FORMAT( 
CURRENT_TIMESTAMP ,  '%y-%m-%d' ) 
ORDER BY  `customerCard`.`cardNumber` ASC 
LIMIT 0 , 30