我有一张id | type | publishedon
的表格
type可以是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
答案 0 :(得分: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`
然后在应用程序中创建所需的格式。