简体   繁体   English

MySQL-从2个表中获取MAX结果的总和

[英]MySQL - getting SUM of MAX results from 2 tables

Here's my problem: I have 2 identical tables (past month data, current month data) - data_2010_03, data_2010_04: 这是我的问题:我有2个相同的表(过去月数据,当月数据)-data_2010_03,data_2010_04:

Content_type (VARCHAR), content_id (INT), month_count (INT), pubDate (DATETIME)

Data in month_count is updated hourly, so for each combination of content_type and content_id we insert new row, where value of month_count is incrementally updated. month_count中的数据每小时更新一次,因此对于content_typecontent_id每种组合,我们插入新行,其中month_count值将递增更新。

Now I try something like this: 现在我尝试这样的事情:
SELECT MAX(t1.month_count) AS max_1, MAX(t2.month_count) AS max_2, SUM(max_1 + max_2) AS result, t1.content_type, t1.content_id
FROM data_2010_03 AS t1
JOIN data_2010_04 AS t2 ON t1.content_type = t2.content_type AND t1.content_id = t2.content_id
WHERE t2.pubDate < '2010-04-08' AND t1.content_type = 'video'
GROUP BY t1.content_id
ORDER BY result desc, max_1 desc, max_2 desc
LIMIT 0,10

I get an error "Unknown column 'max_1' in 'field list'. Please help. 我收到一个错误“字段列表中的未知列'max_1'。请帮助。

You can not use aliases in expressions (on the same level of select) so 您不能在表达式中使用别名(在选择级别相同),因此

SUM(max_1 + max_2) AS result

has to be written as 必须写成

MAX(t1.month_count)+MAX(t2.month_count) AS result

Instead of 代替

SELECT MAX(t1.month_count) AS max_1, MAX(t2.month_count) AS max_2, SUM(max_1 + max_2) AS result

Can you just do 你能做

SELECT MAX(t1.month_count) + MAX(t2.month_count) AS result

Or I may have misunderstood the requirement. 否则我可能会误解了该要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM