MySQL别名子查询

时间:2018-10-04 06:53:22

标签: mysql sql aliases

我有一个仅包含两列的表: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,但这是一种简化方案,可以为别名子查询找到正确的语法。

2 个答案:

答案 0 :(得分:2)

尝试以下方法:由于您合并了所有结果,因此只需要一个别名

SELECT id, cnt
FROM
(
    SELECT id1 AS id, COUNT(id1) AS cnt
    FROM my_table 
    GROUP BY id1
    UNION ALL
    SELECT id2, COUNT(id2)
    FROM my_table
    GROUP BY id2
) AS tab;

答案 1 :(得分:1)

为解决这个问题,这里是您需要合并两个派生表的语法:

SELECT id, cnt
FROM
(
    SELECT id1 AS id, COUNT(id1) AS cnt
    FROM my_table 
    GROUP BY id1
) AS tab1
UNION ALL
SELECT id, cnt
FROM
(
    SELECT id2 AS id, COUNT(id2) AS cnt
    FROM my_table
    GROUP BY id2
) AS tab2;

Demo

您需要为UNION中的子查询的 each 组件显式选择语句。当然,@ fa06的答案就是您应该使用的答案,但是如果您需要走这条路,以上就是您将如何使用它的方法。