【发布时间】:2017-10-29 05:50:24
【问题描述】:
我有两张桌子user_profile 和tracked_search。 user_profile 表包含用户详细信息,tracked_search 跟踪每个用户进行的搜索。
每当用户进行搜索时,此搜索条目都会进入tracked_search 表。如果没有针对特定日期搜索任何内容,则不会在 tracked_search 中添加任何内容。
我需要开发一个报告,我需要在其中显示一个月的所有日子有多少用户进行了搜索。
例如:
CREATE TABLE tracked_search (
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
created DATE,
user_id int NOT NULL
);
INSERT INTO tracked_search(created, user_id) VALUES
('2017-10-01', 1000),
('2017-10-01', 1000),
('2017-10-01', 2000),
('2017-10-01', 3000),
('2017-10-01', 4000),
('2017-10-04', 1000),
('2017-10-04', 2000),
('2017-10-04', 2000),
('2017-10-04', 2000),
('2017-10-04', 2000),
('2017-10-04', 3000),
('2017-10-31', 1000),
('2017-10-31', 2000),
('2017-10-31', 3000),
('2017-10-31', 4000),
('2017-10-31', 5000);
期望的输出:
Date user_count
2017-10-01 4
2017-10-02 0
2017-10-03 0
2017-10-04 3
2017-10-05 0
...
2017-10-30 0
2017-10-31 5
我写了以下查询
SELECT ts.created , count( distinct ts.user_id) FROM tracked_search ts, user_profile u
WHERE ts.created>=(CURDATE()-INTERVAL 1 MONTH) AND u.id = ts.user_id
group by ts.created;
但我明白了
Date user_count
2017-10-01 4
2017-10-04 3
2017-10-31 5
如果特定日期没有条目,我需要打印所有天的值,它应该为零。
我正在使用 MySQL。
【问题讨论】:
-
数据显示问题通常最好在应用程序代码中解决,如果有的话。
-
但我需要每天发送数据。在java中,我将不得不检查哪些日期不存在,然后将那些日期为零的日期插入列表中。这个过程是可以避免的。
标签: mysql