什么是正确的查询

时间:2015-11-25 14:40:03

标签: mysql

我的查询如下:

SELECT j_stats.j_id, js.title, j_stats.date_viewed, COUNT(j_stats.date_viewed) AS num 
FROM js 
INNER JOIN j_stats 
WHERE j_stats.j_id = 3 and js.j_id = 3;

它返回:

j_id | title   | date_viewed | num
  3  | <title> |  2015:11:24 |  18

但是,我想将视图数量分成每个date_viewed的视图数量而不是视图总数,以便它看起来像这样:

j_id | title   | date_viewed | num
  3  | <title> |  2015:11:24 |  6
  3  | <title> |  2015:11:23 |  4
  3  | <title> |  2015:11:22 |  5
  3  | <title> |  2015:11:21 |  3

我已尝试按date_viewed进行分组,但无法正确使用语法(我不确定这是此查询的前进方式,或者......)我有点新手使用MySQL,无法获得我需要的格式。如何更改查询以获得我需要的结果?

提前致谢!

3 个答案:

答案 0 :(得分:2)

您忘了在最后添加GROUP BY

GROUP BY j_stats.date_viewed

这会根据每个日期对COUNT的结果进行分组。休息很好

答案 1 :(得分:0)

尝试此查询以获得所需的结果

SELECT j_stats.j_id, js.title, j_stats.date_viewed, count(j_stats.date_viewed) AS num FROM js inner JOIN j_stats WHERE j_stats.j_id = 3 and js.j_id = 3 group by j_stats.date_viewed;

答案 2 :(得分:0)

您可以使用group by:

SELECT j_stats.j_id, js.title, j_stats.date_viewed, count(j_stats.date_viewed) AS num FROM js inner JOIN j_stats WHERE j_stats.j_id = 3 and js.j_id = 3 group by j_stats.date_viewed;