连接表的 SQL 别名

标签 sql sql-server join alias outer-join

我有一个这样的查询:

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/

相关文章:

c# - 如何合并两个列表并删除重复项

mysql - Where 子句中的 SQL 更改条件

MySQL:多个查询一个输出

sql - 如何在 Oracle 中添加日期和时间

sql - 过滤一组记录

java - Spring JPA : Select specific columns on join with annotation/JPQL

sql - T-SQL : How to log erroneous entries during import

sql-server - SSRS : repeat tablix left-most row group value on each row

sql - 将交易记录分组到一个单元格中

sql - 连接中的嵌套选择 : The multi-part identifier could not be bound