您只需要输入所有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`
然后在应用程序中创建所需的格式。