SQL选择匹配记录存在的位置,没有匹配的记录

时间:2010-10-05 16:25:54

标签: sql sql-server

我需要交叉引用2个表。

tb1内的

是booking_ref,投资者

在tb2内是booking_ref,投资者,成本

问题是如果没有成本,表2中没有创建记录

所以我有以下查询......

SELECT 
  tb1.booking_ref, tb1.investor, tb2.cost 
FROM 
  tb1, tb2 
WHERE 
  tb1.booking_ref = tb2.booking_ref 
AND 
  tb1.investor = tb2.investor 
AND 
  tb1.investor = ''12345''

这会显示tb2中匹配的booking_ref的所有预订,但我还需要显示没有匹配的booking_ref的预订

任何想法??

7 个答案:

答案 0 :(得分:6)

在这种情况下,你想要一个左连接。

SELECT 
  tb1.booking_ref, tb1.investor, tb2.cost 
FROM 
  tb1
      left join tb2 
          on tb1.booking_ref = tb2.booking_ref
              and tb1.investor = tb2.investor 
WHERE tb1.investor = ''12345''

答案 1 :(得分:4)

LEFT JOIN

我打算发布一个例子,但是有几个人打败了我。

但是,仅仅是一个FYI,您的帖子使用了隐式INNER JOIN语法。答案/示例使用的是所谓的显式JOIN语法。

Explicit vs implicit SQL joins

我习惯一直使用Explicit JOIN语法,即使对于INNER JOIN s,它看起来更令人困惑,但它更加一致,因为你需要将它用于LEFT JOINFULL OUTER JOIN秒。

顺便说一下,LEFT JOIN是LEFT OUTER JOIN的同义词,但确切的语法取决于你的RDBMS。 RIGHT JOIN在技术上是多余的,因为您仍然可以使用LEFT JOIN个关键字,只需在SQL中反转表的顺序。

答案 2 :(得分:1)

select t1.booking_ref, t1.investor, t2.cost
from tb1 t1
left join tb2 t2 
     on t1.booking_ref = t2.booking_ref
     and t1.investor = t2.investor
where t1.investor = '12345'

答案 3 :(得分:0)

LEFT JOIN 是你的男人 -

SELECT 
  tb1.booking_ref, tb1.investor, tb2.cost 
FROM 
  tb1 LEFT JOIN tb2 
ON
  tb1.booking_ref = tb2.booking_ref 
AND 
  tb1.investor = tb2.investor 
AND 
  tb1.investor = '12345'

答案 4 :(得分:0)

试试这个:

SELECT  tb1.booking_ref, 
          tb1.investor, 
          tb2.cost 
FROM      tb1 left outer join
          tb2 on tb1.booking_ref = tb2.booking_ref
where    tb1.investor = tb2.investor
and    tb1.investor = '12345'
and (       tb1.booking_ref = tb2.booking_ref
        or     tb2.booking_ref is null)

答案 5 :(得分:0)

看一下SQL提供的不同类型的Joins,例如Left Join,Right Join,Full Join。本网站有一个很好的参考资料可以帮助您入门:http://www.w3schools.com/sql/sql_join.asp。了解每个联接将帮助您完成的任务,一旦您这样做,我相信您会得到答案。

答案 6 :(得分:0)

服务器没有说明......但如果他在8i之前在Oracle中,我认为内部或左连接语法不起作用。如果您处于早期的oracle版本,请使用(+)进行外连接。

选择
  tb1.booking_ref,tb1.investor,tb2.cost

  tb1,tb2
WHERE
  tb1.booking_ref = tb2.booking_ref

  tb1.investor = tb2.investor(+) 和
  tb1.investor ='''12345''

(我认为没错......无法验证)

相关问题