从多个表中选择,但按日期时间字段排序

时间:2011-11-22 09:40:14

标签: mysql sql

我有3个不相关的表(相关,每个表包含不同社交网络的数据)。每个都有一个日期时间字段日期 - 我已经按小时分组,如下所示(下面这个为linked_in)

SELECT count(*), date_format(dated, '%Y:%m:%d %H') as hour
FROM upd8r_linked_in_accts
WHERE CAST(dated AS DATE) = '".$start_date."'
GROUP BY hour

我想知道如何在所有3个网络中进行总计 - 这三个网络的表格是

CREATE TABLE IF NOT EXISTS `upd8r_facebook_accts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_id` varchar(50) NOT NULL,
  `user_id` int(11) NOT NULL,
  `fb_id` bigint(30) NOT NULL,
  `dated` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=80 ;

CREATE TABLE IF NOT EXISTS `upd8r_linked_in_accts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_id` varchar(50) NOT NULL,
  `user_id` int(11) NOT NULL,
  `linked_in` varchar(200) NOT NULL,
  `oauth_secret` varchar(100) NOT NULL,
  `first_count` int(11) NOT NULL,
  `second_count` int(11) NOT NULL,
  `dated` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=200 ;

CREATE TABLE IF NOT EXISTS `upd8r_twitter_accts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_id` varchar(50) NOT NULL,
  `user_id` int(11) NOT NULL,
  `twitter` varchar(200) NOT NULL,
  `twitter_secret` varchar(100) NOT NULL,
  `dated` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

这样的事情?

(SELECT count(*), date_format(dated, '%Y:%m:%d %H') as hour
 FROM upd8r_linked_in_accts 
 WHERE CAST(dated AS DATE) = '".$start_date."')
UNION ALL
(SELECT count(*), date_format(dated, '%Y:%m:%d %H') as hour
 FROM upd8r_facebook_accts
 WHERE CAST(dated AS DATE) = '".$start_date."')
UNION ALL
(SELECT count(*), date_format(dated, '%Y:%m:%d %H') as hour 
 FROM upd8r_twitter_accts 
 WHERE CAST(dated AS DATE) = '".$start_date."')
UNION ALL
GROUP BY hour

更新

实际数据库中的数据与任何pk或fk无关,但数据与每个表代表通过应用程序注册社交网络的用户有关,因此我需要显示每小时注册的用户数量所有三个表

更新2

查询的输出应该显示%Y:%m:%d%H以及三个表中每小时注册的用户数量(创建的记录)...每小时返回一个新行(按时间排序)

1 个答案:

答案 0 :(得分:3)

您接近解决方案

select t1.hourx, sum(t1.column1)
from (
  (
    SELECT count(*) as column1, date_format(dated, '%Y:%m:%d %H') as hourx 
    FROM upd8r_linked_in_accts 
    WHERE CAST(dated AS DATE) = '".$start_date."'
    GROUP BY hourx 
  ) 
  UNION ALL 
  (
    SELECT count(*) as column1, date_format(dated, '%Y:%m:%d %H') as hourx 
    FROM upd8r_facebook_accts 
    WHERE CAST(dated AS DATE) = '".$start_date."'
    GROUP BY hourx
  ) 
  UNION ALL 
  (
    SELECT count(*) as column1, date_format(dated, '%Y:%m:%d %H') as hourx
    FROM upd8r_twitter_accts 
    WHERE CAST(dated AS DATE) = '".$start_date."'
    GROUP BY hourx
  ) 
) t1
GROUP BY t1.hourx

我使用'hourx'来避免保留词,也许没必要。

我希望这有效。

[ADD] 此解决方案称为“内联视图”。你可以google。它受大多数数据库(mysql,oracle mssql等)支持