我有一个这样的查询:
select a1.name, b1.info
from (select name, id, status
from table1 a) as a1
right outer join (select id, info
from table2 b) as b1 on (a1.id = b1.id)
我只想包含 a1.status=1 的所有内容,并且由于我使用的是外连接,所以我不能只向 table1 添加 where
约束,因为来自 table2 的所有信息我想要被排除的人仍然会在那里,只是没有名字。我在想这样的事情:
select z1.name, z1.info
from ((select name, id, status
from table1 a) as a1
right outer join (select id, info
from table2 b) as b1 on (a1.id = b1.id)) as z1
where z1.status = 1
但我认为这是不合法的。
编辑: 如下所述,外部联接实际上对于我想要做的事情没有意义。例如,如果我想要 table2 中 table1 中 status!=1 的所有数据,包括 table1 中根本不存在相应 ID 的所有数据,该怎么办?因此,我需要对 table2 中的所有数据进行外连接,但仍想排除那些 status=1 的条目。
相当于:
select z1.name, z1.info
from ((select name, id, status
from table1 a) as a1
right outer join (select id, info
from table2 b) as b1 on (a1.id = b1.id)) as z1
where z1.status != 1
最佳答案
SELECT a1.Name, b1.Info
FROM table2 b1
JOIN table2 a1 ON b1.id= a1.id AND a1.status = 1
右外部联接与左外部联接执行完全相同的操作,只是交换了表。您可以对联接进行过滤,它仍然会包含初始表中的数据。
关于连接表的 SQL 别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4071909/