连接表的SQL别名

时间:2010-11-01 18:34:13

标签: 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

3 个答案:

答案 0 :(得分:12)

SELECT a1.Name, b1.Info
FROM table2 b1
    JOIN table2 a1 ON b1.id= a1.id AND a1.status = 1

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

答案 1 :(得分:2)

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)

答案 2 :(得分:0)

select a1.name, b1.info from
(select name, id, status from table1 a WHERE status=1) as a1
right outer join
(select id, info from table2 b) as b1 on (a1.id=b1.id)

编辑:

对于你的第二个场景:

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)
EXCEPT
select a1.name, b1.info from
(select name, id, status from table1 a WHERE status<>1) as a1
right outer join
(select id, info from table2 b) as b1 on (a1.id=b1.id)

这应该有效,因为无论如何都会获得所有table2数据。

编辑2:

好的,从表2中获取所有内容除了表1中有状态ID之外,即使table1中没有条目,也需要使用EXCEPT函数,它基本上会从更大的数据集。