MySQL UNION - 每个派生表必须有自己的别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25340979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:58:49  来源:igfitidea点击:

MySQL UNION - Every derived table must have its own alias

mysqlsqlselectgroup-byunion

提问by user3270967

I am looking for a solution:

我正在寻找解决方案:

SELECT SUM(`quant`), MONTH(`date`) AS month, `id` from (
(SELECT `date`, `id`, count(`hit`) AS `quant ` FROM `stat_2014_07` WHERE `k_id` = '123') 
UNION ALL 
(SELECT `date`, `id`, count(`hit`) AS `quant ` FROM `stat_2014_08` WHERE `k_id ` = '123') 
) group by id, month

MySQL: Every derived table must have its own alias

MySQL:每个派生表都必须有自己的别名

回答by Mureinik

You need to give aliases to your queries:

您需要为您的查询提供别名:

SELECT   SUM(`quant`), MONTH(`date`) AS month, `id` 
FROM     ((SELECT `date`, `id`, count(`hit`) AS `quant` 
           FROM   `stat_2014_07` 
           WHERE  `k_id` = '123') t1
          UNION ALL 
          (SELECT `date`, `id`, count(`hit`) AS `quant` 
           FROM   `stat_2014_08` 
           WHERE  `k_id ` = '123') t2
         ) t_union
GROUP BY id, month

回答by a_horse_with_no_name

Exactly what the error message says. In your (simplified) query:

正是错误消息所说的。在您的(简化)查询中:

SELECT SUM(`quant`), MONTH(`date`) AS month, `id` 
from (
  ... inner select 
) 
group by id, month;

You didn't specify an alias for the derived table. So it should be:

您没有为派生表指定别名。所以应该是:

SELECT SUM(`quant`), MONTH(`date`) AS month, `id` 
from (
  ... inner select 
) as t -- this is the change
group by id, month;

Btw: the parentheses around the select parts of a union are totally useless. I suggest removing them for clarity:

顺便说一句:联合选择部分周围的括号完全没用。为了清楚起见,我建议删除它们:

SELECT SUM(`quant`), MONTH(`date`) AS month, `id` 
from (
  SELECT `date`, `id`, count(`hit`) AS `quant ` FROM `stat_2014_07` WHERE `k_id` = '123'
  UNION ALL 
  SELECT `date`, `id`, count(`hit`) AS `quant ` FROM `stat_2014_08` WHERE `k_id ` = '123'
) as t -- this is the change
group by id, month;