Reputation: 12988
I need to cross reference 2 tables.
within tb1 is booking_ref, investor
within tb2 is booking_ref, investor, cost
The trouble is if there in no cost, no record is created in table 2
So I have the following query...
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''
this displays all bookings where there is a matching booking_ref in tb2 but I also need to display bookings where there is not a matching booking_ref
any ideas??
Upvotes: 2
Views: 1126
Reputation: 7180
Server isn't stated...but if he's in Oracle prior to 8i, I don't think inner or left join syntax will work. If you are in early oracle versions, use the (+) for outer joins.
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''
(I think thats right...unable to verify)
Upvotes: 0
Reputation: 12369
LEFT JOIN is your man-
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'
Upvotes: 0
Reputation: 18962
I was going to post an example, but several people beat me to it.
However, just an FYI, your post is using the Implicit INNER JOIN
syntax. The answers/examples are using what's known as the Explicit JOIN
syntax.
Explicit vs implicit SQL joins
I am in the habit of always using the Explicit JOIN syntax, even though for INNER JOIN
s, it's more confusing looking, but it's more consistent, because you need to use it for LEFT JOIN
s and FULL OUTER JOIN
s.
Btw, LEFT JOIN is synonymous with LEFT OUTER JOIN, but the exact syntax depends on your RDBMS. And RIGHT JOIN is technically superfluous, because you can still use LEFT JOIN
keywords and just reverse the order of your tables in your SQL.
Upvotes: 4
Reputation: 145
Take a look at the different types of Joins SQL offers you such as Left Join, Right Join, Full Join. This site has a good reference to help you get started: http://www.w3schools.com/sql/sql_join.asp. Understand what each of the joins will help you accomplish, and once you do, I believe you will have your answer.
Upvotes: 0
Reputation: 514
Try this:
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)
Upvotes: 0
Reputation: 38506
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'
Upvotes: 1
Reputation: 135729
You want a left join in this case.
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''
Upvotes: 6