连接表的SQL别名

Lin*_*cum 6 sql sql-server alias join 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)
Run Code Online (Sandbox Code Playgroud)

我只想包含a1.status = 1的所有内容,因为我正在使用外连接,所以我不能只where为table1 添加一个约束,因为我想要排除的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
Run Code Online (Sandbox Code Playgroud)

但我不认为这是合法的.

编辑:如下所述,外连接实际上对我正在尝试做的事情没有意义.例如,如果我想要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
Run Code Online (Sandbox Code Playgroud)

Dus*_*ine 12

SELECT a1.Name, b1.Info
FROM table2 b1
    JOIN table2 a1 ON b1.id= a1.id AND a1.status = 1
Run Code Online (Sandbox Code Playgroud)

右外连接与左外连接完全相同,仅切换表.您可以对连接进行过滤,它仍将包含初始表中的数据.


Sam*_*eff 3

添加该where子句,如下所示subquery

select a1.name, b1.info from
(
    select name, id
    from table1 a  
    where a.status = 1
) as a1

right outer join

(
    select id, info 
    from table2 b
) as b1 on (a1.id=b1.id)
Run Code Online (Sandbox Code Playgroud)