从多个表中获取带时间戳的计数

时间:2012-07-30 16:07:30

标签: mysql join count timestamp

我有一个节点表:

nid type  created   status
2   blog  134292319 1
3   forum 134292536 1
4   blog  135921392 0

要绘制已发布(status = 1)节点的数量,我执行此查询:

SELECT created, type
FROM node WHERE status = 1
ORDER BY created

然后,我在PHP中浏览此数据集,将其拆分为带有与每个组关联的节点数的带时间戳的组。结果被缓存,因此执行缓慢不是问题。

我还有一张评论表:

nid timestamp status
2   134292363 1
3   134293234 1

我想将论坛评论计数纳入节点计数图。

要获得评论计数,我会运行此查询:

SELECT timestamp
FROM comments
INNER JOIN node ON comments.nid = node.nid
WHERE
  node.type = 'forum'
  AND comments.status = 1
ORDER BY timestamp

我需要以某种方式组合这两个查询,最终得到(对于给出的示例):

created   type
134292319 blog
134292536 forum
134293234 forum_comment

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

这将为您提供示例输出,但我不确定根据您对问题的描述,它正是您所寻找的。

SELECT created, type FROM
(
   SELECT created, type
   FROM node WHERE status = 1

   UNION ALL

   SELECT timestamp as created, 'forum_comment' as type
   FROM comments
   INNER JOIN node ON comments.nid = node.nid
   WHERE node.type = 'forum'
     AND comments.status = 1
) AS U
ORDER BY U.created