我无法弄清楚查询...
我试图从凭证表中获取总价值。
月份始终以unix时间格式不断变化(上个月或下个月)。
PHP
$date = date('Y-m-d', $unixtime);
$month = date('m', $unixtime);
$year = date('Y', $unixtime);
数据库'user_voucher_history':
history_id | user_id | value | used | datetime(unixtime)
the smallest date record was 2013-05-05!
当前查询
SELECT
IFNULL(SUM(value), 0) AS total
FROM user_voucher_history
WHERE user_id = 2 AND used = 1 AND MONTH(FROM_UNIXTIME(datetime)) < {$month}
上面的代码:当谈到2014年和01月时,它返回0,所以尝试了下面的不同代码,仍然是0。
查询
SELECT
IFNULL(SUM(value), 0) AS total
FROM
user_voucher_history,
( SELECT MIN(DATE(FROM_UNIXTIME(datetime))) FROM user_voucher_history) AS min_date
WHERE
user_id = 2 AND used = 1
AND (DATE(FROM_UNIXTIME(datetime)) BETWEEN min_date AND {$date} )
AND (MONTH(FROM_UNIXTIME(datetime)) < {$month} )
AND (YEAR(FROM_UNIXTIME(datetime)) < {$year} )
请建议!!!
答案 0 :(得分:1)
据我了解,您希望显示与所选YEAR
和MONTH
匹配的正确行
试一试
SELECT
IFNULL(SUM(value), 0) AS total
FROM user_voucher_history
WHERE user_id = 2 AND used = 1 AND
MONTH(FROM_UNIXTIME(datetime)) < {$month} AND
YEAR(FROM_UNIXTIME(datetime)) = {$year}
答案 1 :(得分:0)
我想你想聚合几个月:
SELECT SUM(value)
FROM user_voucher_history
WHERE FROM_UNIXTIME(datetime) BETWEEN :mindate AND :maxdate
GROUP BY MONTH(FROM_UNIXTIME(datetime))
顺便说一下,您确实希望将datetime
的类型更改为DATETIME之类的日期类型。