我需要制作一份报告,提供特定周内使用的每个特定促销代码的计数。示例表结构:
CREATE TABLE `user_promo_codes` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`promo_code` longtext NOT NULL,
`last_updated` datetime NOT NULL,
PRIMARY KEY (`id`),
)
我想要的是对给定周内使用的每个特定促销代码的计数。我现在拥有的:
SELECT promo_code, count(*) AS count
FROM user_promo_codes
WHERE last_updated BETWEEN
FROM_UNIXTIME( # one week ago
UNIX_TIMESTAMP( DATE_SUB( NOW(), INTERVAL 7 DAY ) ) - TIME_TO_SEC( NOW() )
)
AND
FROM_UNIXTIME(
UNIX_TIMESTAMP( NOW() ) - TIME_TO_SEC( NOW() )
)
GROUP BY value
有更有效的方法吗?
答案 0 :(得分:1)
对于您显示的数据类型,这应该适用于 now 之前一周。
SELECT promo_code, COUNT(*) AS count
FROM user_promo_codes
WHERE last_updated BETWEEN DATE_SUB( NOW(), INTERVAL 7 DAY ) AND NOW()
GROUP BY promo_code
旁白:
LONGTEXT
使用promo_code
将确保磁盘上的临时表。最好将其作为VARCHAR(N)
。last_updated
的索引随着桌子的增长而变得非常宝贵。<强>更新强>
使用NOW()
- &gt;最近的Wedneday @ 00:00:00
。
SELECT promo_code, COUNT(*) AS count
FROM user_promo_codes
WHERE last_updated BETWEEN
DATE_SUB( CONCAT( DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE())+5 DAY) ,' 00:00:00'), INTERVAL 7 DAY )
AND
CONCAT( DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE())+5 DAY) ,' 00:00:00')
GROUP BY promo_code
上面的
就是上面的内容CONCAT( DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE())+5 DAY) ,' 00:00:00')
换了NOW()
s。