首页 文章

mysql使用UNION查询中select as where子句的结果

提问于
浏览
0

我有这个列的表A:

id   name      to_include
1    wanted1   null
2    wanted2   wanted1

如果查询是针对wanted2,那么我需要一种方法来使用WHERE子句中的 to_include 列(在本例中为 wanted1 )中的值,我尝试过这样的方法:

SELECT * FROM (
    SELECT * FROM A WHERE name = 'wanted2'
) AS B
UNION
SELECT * FROM A WHERE A.name = B.to_include

出现此错误:'where子句中的未知列'B.to_include'

Expected result: 示例表中包含两行的记录集 .

1 回答

  • 2

    您不能将 UNION 中的先前查询称为别名 . UNION 中的每个查询都是独立处理的,然后将结果组合在一起 .

    UNION 中的第二个查询需要是 JOIN ,并且您需要在执行此操作时重复第一个查询中的条件 .

    SELECT * 
    FROM yourTable WHERE name = 'wanted2'
    
    UNION
    
    SELECT b.*
    FROM yourTable AS a
    JOIN yourTable AS b ON b.name = a.to_include
    WHERE a.name = 'wanted2'
    

    DEMO

相关问题