1

我正在尝试计算两个数据库之间的时间戳,但由于不是我的设计缺陷,一个有重叠的时间戳。

SELECT date(time + INTERVAL 8 HOUR) as day, COUNT(DISTINCT comment)
FROM  news.data
GROUP BY day
    UNION ALL
SELECT date(time + INTERVAL 8 HOUR) as day, COUNT(DISTINCT comment)
FROM`news-backup`.`data`
GROUP BY day
ORDER BY year(day) desc, day(day) DESC
LIMIT 20

似乎发生了什么,两个数据库的范围内都有一些时间戳,因此它们会为某些日期产生单独的计数。所以它会从新闻和新闻备份中计算今天

EX:
date      count
2013-1-15  10
2013-1-15  13
2013-1-14  8
2013-1-13  15

我想要的是

EX:
date      count
2013-1-15  23
2013-1-14  8
2013-1-13  15

这是一个踢球者,我需要它在一个视图中,所以有一些限制(不允许子查询)。想法?不,我无法更改数据库之间发生的数据转储序列

4

1 回答 1

0

您不能将子查询放在视图中,但可以将视图放在视图中。

所以:

create view1 as 
    SELECT date(time + INTERVAL 8 HOUR) as day, 'current' as which, COUNT(DISTINCT comment) as cnt
    FROM  news.data
    GROUP BY day
        UNION ALL
    SELECT date(time + INTERVAL 8 HOUR) as day, 'backup' as which, COUNT(DISTINCT comment) as cnt
    FROM`news-backup`.`data`
    GROUP BY day, which

我不确定您将它们组合在一起的逻辑是:

create view2 as
    select day, max(cnt)  -- sum(cnt)?  prefer current or backup?
    from view1
    group by day
    ORDER BY day desc

禁止子查询的文档在这里。请务必搜索“SELECT 语句不能包含”。

如果您有一个包含所有日期的表,那么以下“荒谬”的 SQL 可能会起作用:

select c.date,
       coalesce( (select count(distinct comment) from news.data where date(time + INTERVAL 8 HOUR) = c.date),
                 (select count(distinct comment) from news_backup.data where date(time + INTERVAL 8 HOUR) = c.date)
               ) as NumComments
from calendar c

此版本假设您首先想要“新”,然后是备份。如果你想要总和,那么你会添加它们。

于 2013-01-15T15:02:19.760 回答