在 Oracle 的 WHERE 子句中访问 WITH..AS 子句的列
Access WITH..AS clause's column in WHERE clause in Oracle
我有 2 个表 :
Table_A
USERCODE|USERMOBILE|USERACCOUNT
001 |0123236556|ACC001
002 |0222222222|ACC002
Table_B
USERCODE|USERMOBILE
001 |0123236556
001 |0444444444
002 |0555555555
我想要以下输出,它按 Table_A.ACCOUNT
过滤
例如USERACCOUNT = ACC001
USERCODE|USERMOBILE
001 |0123236556
001 |0123236556
001 |0444444444
我尝试了以下查询但没有成功:
with tbl as
(select USERCODE,USERMOBILE from Table_A WHERE USERACCOUNT='ACC001' )
select * from tbl
union
select USERCODE,USERMOBILE from Table_B WHERE Table_B.USERCODE = tbl.USERCODE
错误:标识符无效:tbl.USERCODE
有什么方法可以达到我的预期效果吗?
没有办法达到你必须使用 Join -
的预期结果
SELECT USERCODE, USERMOBILE
FROM Table_A
WHERE USERACCOUNT='ACC001'
UNION
SELECT USERCODE, USERMOBILE
FROM Table_B B
JOIN Table_A A ON B.USERCODE = A.USERCODE
当您使用 UNION ALL
时,无法从第二个查询中引用第一个查询。
使用 CTE:
WITH cte(USERCODE, USERMOBILE) AS
(SELECT USERCODE, USERMOBILE FROM Table_A WHERE USERACCOUNT = 'ACC001')
SELECT USERCODE, USERMOBILE FROM cte
UNION ALL
SELECT USERCODE, USERMOBILE
FROM Table_B
WHERE USERCODE = (SELECT USERCODE FROM cte)
如果 CTE 可能 return 超过 1 行,请更改为:
WHERE USERCODE IN (SELECT USERCODE FROM cte)
我有 2 个表 :
Table_A
USERCODE|USERMOBILE|USERACCOUNT
001 |0123236556|ACC001
002 |0222222222|ACC002
Table_B
USERCODE|USERMOBILE
001 |0123236556
001 |0444444444
002 |0555555555
我想要以下输出,它按 Table_A.ACCOUNT
例如USERACCOUNT = ACC001
USERCODE|USERMOBILE
001 |0123236556
001 |0123236556
001 |0444444444
我尝试了以下查询但没有成功:
with tbl as
(select USERCODE,USERMOBILE from Table_A WHERE USERACCOUNT='ACC001' )
select * from tbl
union
select USERCODE,USERMOBILE from Table_B WHERE Table_B.USERCODE = tbl.USERCODE
错误:标识符无效:tbl.USERCODE
有什么方法可以达到我的预期效果吗?
没有办法达到你必须使用 Join -
的预期结果SELECT USERCODE, USERMOBILE
FROM Table_A
WHERE USERACCOUNT='ACC001'
UNION
SELECT USERCODE, USERMOBILE
FROM Table_B B
JOIN Table_A A ON B.USERCODE = A.USERCODE
当您使用 UNION ALL
时,无法从第二个查询中引用第一个查询。
使用 CTE:
WITH cte(USERCODE, USERMOBILE) AS
(SELECT USERCODE, USERMOBILE FROM Table_A WHERE USERACCOUNT = 'ACC001')
SELECT USERCODE, USERMOBILE FROM cte
UNION ALL
SELECT USERCODE, USERMOBILE
FROM Table_B
WHERE USERCODE = (SELECT USERCODE FROM cte)
如果 CTE 可能 return 超过 1 行,请更改为:
WHERE USERCODE IN (SELECT USERCODE FROM cte)