看看这个:
我的SQL查询是:
SELECT @rownum := @rownum + 1 AS ID, SKU, SUM(Quantity) FROM orders, (SELECT @rownum := 0) r
WHERE ShipDate BETWEEN 01-05-2013 AND 11-05-2013
GROUP BY SKU
在我的代码中,我正在执行以下操作:
$sql = "SELECT @rownum := @rownum + 1 AS ID, SKU, SUM(Quantity)
FROM orders, (SELECT @rownum := 0) r
WHERE ShipDate BETWEEN {$from_date } AND {$to_date }
GROUP BY SKU";
我想选择介于两个值之间的数据。
ShipDate
是一个文本字段,而不是日期字段。我检查了表,它保存数据,但MySQL返回null。
为什么呢?我做错了什么?
如何更新我的PHP代码?
此代码:
"SELECT @rownum := @rownum + 1 AS ID, SKU, SUM(Quantity)
FROM orders, (SELECT @rownum := 0) r
WHERE STR_TO_DATE(ShipDate,'%d-%m-%Y') BETWEEN {$from_date } AND {$to_date }
GROUP BY SKU";
不适合我。
请帮帮我。
答案 0 :(得分:3)
使用STR_TO_DATE()将文本转换为日期
SELECT @rownum := @rownum + 1 AS ID,
SKU,
SUM(Quantity)
FROM orders, (SELECT @rownum := 0) r
WHERE STR_TO_DATE(ShipDate,'%d-%m-%Y') BETWEEN '2013-05-01' AND '2013-05-11'
GROUP BY SKU
并在日期周围添加引号,并将日期重新排列为yyyy-mm-dd
答案 1 :(得分:1)
由于ShipDate是文本字段,因此在文本数据的情况下未正确评估BETWEEN
运算符,因此查询失败。使用STR_TO_DATE()