【发布时间】:2019-03-09 11:47:55
【问题描述】:
我有一个只包含两列的表:id1 和 id2。 MySQL 中的以下查询可以正常工作:
(select id1 as id, count(id1) as cnt
from my_table
group by id1)
union all
(select id2 as id, count(id2) as cnt
from my_table
group by id2)
如果我想将上面的查询用作子查询,我需要为每个派生表设置别名 - 下面的代码会出错(“每个派生表都必须有自己的别名”):
select id, cnt from
(select id1 as id, count(id1) as cnt
from my_table
group by id1)
union all
(select id2 as id, count(id2) as cnt
from my_table
group by id2)
但是我找不到正确的语法来给派生表起别名。我正在尝试添加和删除括号,但到目前为止还没有运气。对于下面的查询,我只是得到一般的 SQL 语法错误:
select id, cnt from
(select id1 as id, count(id1) as cnt
from my_table
group by id1) as tab1
union all
(select id2 as id, count(id2) as cnt
from my_table
group by id2) as tab2
稍后我会想用这个子查询做更多的事情,而不是只选择 id 和 cnt,但它是一个简化的场景,可以找到别名子查询的正确语法。
【问题讨论】:
-
我确定不是“它是”!