gpt4 book ai didi

MySQL 别名子查询

转载 作者:行者123 更新时间:2023-11-29 05:03:42 25 4
gpt4 key购买 nike

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

最佳答案

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

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;

关于MySQL 别名子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52640719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com