SQL 重命名列的 UNION

SQL UNION with renamed columns

我尝试创建一个新的 table,c,将 user1 重命名为 user2,将 user2 重命名为用户 1 并 UNION ALL 原来的 table.

WITH c AS 
(
    SELECT 
        user1 AS user2, user2 AS user1, msg_count 
    FROM f
) 
SELECT * 
FROM c 
UNION ALL 
(SELECT user1, user2, msg_count 
 FROM f)

这是f,原table:

id date user1 user2 msg_count
1 2020-08-02 kpena scottmartin 2
2 2020-08-02 misty19 srogers 2
3 2020-08-02 jerome75 craig23 3

问题是:为什么我没有得到重命名列 table 到 UNION?我的查询返回了两个相同原始 tables

的 UNION

输出是这样的:

id user2 user1 msg_count
1 kpena scottmartin 2
2 misty19 srogers 2
3 jerome75 craig23 3
4 kpena scottmartin 2
5 misty19 srogers 2
6 jerome75 craig23 3

这不是我所期望的,我期待的是:

id user2 user1 msg_count
1 kpena scottmartin 2
2 misty19 srogers 2
3 jerome75 craig23 3
4 scottmartin kpena 2
5 srogers misty19 2
6 craig23 jerome75 3

有人可以解释一下吗?

非常感谢!

不需要 CTE

您只需为用户 1 和两个切换列:

(SELECT user1 AS user2, user2 AS user1, msg_count FROM f)
UNION ALL (SELECT user2, user1, msg_count FROM f)

您的查询添加了两次相同的结果,但正如我已经写过的那样,第二个查询必须将 user1 和 user2 颠倒才能得到您的结果

为了解释这个问题,请考虑仅从 CTE 中选择的输出 - 您已重命名列,但顺序(从左到右)保持不变,所以现在考虑 select *...

您想要的结果取决于您选择了正确的列,而不是它们的顺序:

with c as (select user1 as user2, user2 as user1, msg_count from f) 
select user1, user2, msg_count
from c 
union all (select user1, user2, msg_count from f);