我正在尝试按时间间隔计算观看次数。以下请求仅在没有AND
子句的情况下有效
如果我取出AND s.timestamp < 2019-01-31
,它就可以正常工作。
SELECT s.category_id, c.name, count(s.category_id) AS ViewCount
FROM stat_product_category s
JOIN category c ON s.category_id = c.id
WHERE s.timestamp > 2019-01-01 AND s.timestamp < 2019-01-31
GROUP BY s.category_id
ORDER By ViewCount Desc
LIMIT 10
答案 0 :(得分:2)
您需要在日期值上加上单引号
SELECT s.category_id, c.name, count(s.category_id) AS ViewCount
FROM stat_product_category s
JOIN category c ON s.category_id = c.id
WHERE s.timestamp > '2019-01-01' AND s.timestamp <'2019-01-31'
GROUP BY s.category_id ,c.name
ORDER By ViewCount Desc
LIMIT 10
答案 1 :(得分:2)
那些不是时间戳-没有引号,您只需要减去几个整数即可。将2019-01-01评估为2019-1-1或2017.将2019-01-31评估为2019-1-31或1987.没有大于2017的数字但小于1987的数字,因此得到没有结果。这些值用引号引起来将使它们成为字符串文字,并允许数据库执行隐式转换为日期:
SELECT s.category_id, c.name, count(s.category_id) AS ViewCount
FROM stat_product_category s
JOIN category c ON s.category_id = c.id
WHERE s.timestamp > '2019-01-01' AND s.timestamp < '2019-01-31'
-- Here ------------^----------^-------------------^----------^
GROUP BY s.category_id
ORDER By ViewCount Desc
LIMIT 10
答案 2 :(得分:0)
该脚本看起来不错,您只需要在日期周围弹出qoutes即可,以便SQL知道值在何处开始和结束。
SELECT s.category_id, c.name, count(s.category_id) AS ViewCount
FROM stat_product_category s
JOIN category c ON s.category_id = c.id
WHERE s.timestamp > '2019-01-01' AND s.timestamp < '2019-01-31'
GROUP BY s.category_id
ORDER By ViewCount Desc
LIMIT 10
(经测试可正常工作!)
项目进展顺利!