我正在尝试计算两个数据库之间的时间戳,但由于不是我的设计缺陷,因此有一个时间戳重叠。
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
这是一个踢球者,我在视图中需要它,因此有一些限制(不允许子查询)。思考?不,我不能改变DB之间发生的数据转储序列
答案 0 :(得分: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
禁止子查询的文档是here。请务必搜索“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
此版本假设您首先需要“新”,然后是备份。如果你想要总和,那么你可以添加它们。