连接表的 SQL 别名
我有一个这样的查询:
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
但我认为这是不合法的。
编辑: 如下所述,外部联接实际上对于我想要做的事情没有意义。例如,如果我想要 table1 中 status!=1 的 table2 中的所有数据,包括 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
I have a query like this:
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)
I only want to include everything where a1.status=1 and since I'm using an outer join, I can't just add a where
constraint to table1, because all info from table2 that I want to be excluded will still be there, just without the name. I was thinking something like this:
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
but I don't think that's legal.
EDIT:
As described below, an outer join actually doesn't make sense for what I'm trying to do. What if, for example, I want all the data from table2 where status!=1 in table1, inclusive of all data where a corresponding ID does not at all exist in table1. Thus I would need an outer join of all data from table2, but still want to exclude those entries where the status=1.
Equivalent to this:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
右外连接与左外连接执行完全相同的操作,只是交换了表。您可以对连接进行过滤,它仍然会包含初始表中的数据。
A right outer join does the exact same thing as a left outer join, with just the tables switched. You can filter on the join and it will still include the data from the initial table.
将
where
子句添加到subquery
中,如下所示:Add the
where
clause to thesubquery
like this:编辑:
对于您的第二种情况:
这应该有效,因为无论如何您都会获得所有 table2 数据。
编辑2:
好的,要从表2中获取除表1中存在状态ID之外的所有内容,即使表1中没有条目,您也需要使用
EXCEPT
函数,该函数基本上会排除较大数据集的子集。EDIT:
For your second scenario:
That should work since you will get all the table2 data regardless.
EDIT 2:
OK, to get everything from table2 EXCEPT where there is a status ID in table 1, even if there is not an entry in table1, you need to use the
EXCEPT
function, which will basically exclude a subset from a larger dataset.