如何在 Oracle 中编写带有连接和别名的查询?

How to write queries with concatenation and alias in Oracle?

我有两个表 A 和 B,架构如下:-

Table A -> 两列 Principal (varchar) 和 LoginTime (Timestamp)

Table B -> 两列用户名(varchar)和登录时间(时间戳)

现在我必须 运行 对两个表进行查询,合并它们,然后按用户名排序。所以我写了一个这样的查询:-

select Principal AS Uname || ', ' ||
       LoginTime from A
       where LoginTime > 1430890465
UNION ALL
select Username AS Uname || ', ' ||
       LoginTime from B
       where LoginTime > 1430890465
order by Uname;

但上面的方法似乎不起作用并给出以下错误:-

ORA-00923: FROM keyword not found where expected 00923. 00000 - "FROM keyword not found where expected" *Cause:
*Action:

as 位于您要为其指定别名的列之后:

select Principal  || ', ' || LoginTime  AS Uname
from A
where LoginTime > 1430890465

union all

select Username || ', ' || LoginTime
from B
where LoginTime > 1430890465

Principal AS Uname || ', ' || LoginTime

语法不正确。您可以连接两列。您不能将一列与另一列的别名连接起来。

由于您连接的是 usernametimestamp 列,因此您只需将 别名 添加到 连接的列,即表达式.

select (Principal || ', ' ||
       LoginTime) AS Uname from A
       where LoginTime > 1430890465
UNION ALL
select (Username || ', ' ||
       LoginTime) AS Uname from B
       where LoginTime > 1430890465
order by Uname;

我已将大括号添加到表达式中,即串联的列,以便您轻松理解 别名 Uname 用于 连接值.