mysql别名子查询

i2byvkas  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(333)

我有一个只包含两列的表: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,但是找到正确的别名子查询语法是一个简化的场景。

hpxqektj

hpxqektj1#

试试下面的方法:因为你合并了所有的结果,所以你只需要一个别名

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;
tf7tbtn2

tf7tbtn22#

为了解决这个问题,以下是合并两个派生表所需的语法:

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;

演示

对于中的子查询的每个组件,都需要显式的select语句 UNION . 当然,@fa06的答案是您应该使用的,但是如果您需要沿着这条路走下去,上面是您将如何使它工作的。

相关问题