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

Tom*_*Tom 2 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''
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗??

Joe*_*lli 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''
Run Code Online (Sandbox Code Playgroud)