MySQL UNION - 每个派生表都必须有自己的别名
Posted
技术标签:
【中文标题】MySQL UNION - 每个派生表都必须有自己的别名【英文标题】:MySQL UNION - Every derived table must have its own alias 【发布时间】:2014-10-10 01:10:01 【问题描述】:我正在寻找解决方案:
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:每个派生表都必须有自己的别名
【问题讨论】:
您可以添加一个别名,方法是在关闭)
后为子查询指定一个名称。所以,像(SELECT foo FROM bar) thisisaderivedtablealias
这样的东西。您可以在 UNION ALL BTW 中省略 2 个内部查询周围的 ()
。
具有相同结构但名称不同的表通常表示数据库设计不佳。如果您有一个名为stats
的表包含所有月份的数据,则不需要union all
。
【参考方案1】:
正是错误消息所说的内容。在您的(简化的)查询中:
SELECT SUM(`quant`), MONTH(`date`) AS month, `id`
from (
... inner select
)
group by id, month;
您没有为派生表指定别名。所以应该是:
SELECT SUM(`quant`), MONTH(`date`) AS month, `id`
from (
... inner select
) as t -- this is the change
group by id, month;
顺便说一句:联合的选定部分周围的括号完全没用。为了清楚起见,我建议删除它们:
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;
【讨论】:
【参考方案2】:您需要为查询指定别名:
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
【讨论】:
以上是关于MySQL UNION - 每个派生表都必须有自己的别名的主要内容,如果未能解决你的问题,请参考以下文章