1

我有一个id | type | publishedon 类型可能是 1,2,3 或 4 (int) 值的表我想为现在使用的每一天选择帖子

SELECT FROM_UNIXTIME( `publishedon` , "%Y-%m-%d" ) AS `day` , count( id ) AS listings,
TYPE FROM posts
WHERE (
FROM_UNIXTIME( publishedon ) >= SUBDATE( NOW( ) , 30 )
)
GROUP BY `day`

结果

day     listings
2013-09-02  17
2013-09-05  105

我想让列表提交得更详细,比如

day     type_1   type_2   type_3   type_4
2013-09-02  10      4       6        3
2013-09-05  6      4       1        3
4

1 回答 1

1

您只需要输入所有type值:

SELECT 
  FROM_UNIXTIME( `publishedon` , "%Y-%m-%d" ) AS `day`, 
  count(id) AS listings,
  (SELECT COUNT(id) FROM `posts` WHERE `type`=1 AND FROM_UNIXTIME(`publishedon`, "%Y-%m-%d")=`day`) AS `type_1`,
  (SELECT COUNT(id) FROM `posts` WHERE `type`=2 AND FROM_UNIXTIME(`publishedon`, "%Y-%m-%d")=`day`) AS `type_2`,
  (SELECT COUNT(id) FROM `posts` WHERE `type`=3 AND FROM_UNIXTIME(`publishedon`, "%Y-%m-%d")=`day`) AS `type_3`,
  (SELECT COUNT(id) FROM `posts` WHERE `type`=4 AND FROM_UNIXTIME(`publishedon`, "%Y-%m-%d")=`day`) AS `type_4`
FROM 
  `posts`
WHERE
  FROM_UNIXTIME(`publishedon`) >= SUBDATE(NOW(), 30)
GROUP BY 
  `day`

但实际上,这将运行缓慢,因为条件中有函数。如果只是格式问题,最好采取如下方式:

SELECT 
  FROM_UNIXTIME(`publishedon`, "%Y-%m-%d" ) AS `day`, 
  `type`,
  count( id ) AS listings,
FROM 
  `posts`
WHERE
-- this should be better evaluated in application 
-- since will not produce index using too:
  FROM_UNIXTIME(`publishedon`) >= SUBDATE(NOW(), 30)
GROUP BY 
  `day`,
  `type`

然后在应用程序中创建所需的格式。

于 2013-09-06T13:06:17.053 回答