Winten
Winten

Reputation: 664

SQL optional parameter?

Lets say I have two tables:

Table1

Id Name
1 Joe
2 Greg
3 Susan
4 Max

Table2

Uid comment
2    Good customer
4    Great guy

What I want to do is list all elements of Table 1, and if Table1.Id = Table2.Uid I want to select this comment. If comment does not exist give blank field.

Result should be:

1 Joe 
2 Greg Good customer
3 Susan
4 Max Great Guy

I can't figure out how to do it, if I write:

select
table1.Id,
table1.Name,
table2.comment

where
table1.id=table2.Uid

It gives me only users 2 and 4.

Upvotes: 1

Views: 494

Answers (3)

Robert
Robert

Reputation: 25753

Try to use left join it shows you all data from table1

select t1.Id, t1.Name, t2.comment
from table1 t1
left join table2 t2 on t1.id=t2.Uid

NOTE:

Good practice is to use aliases as above. Code is more readable.

Upvotes: 4

zkanoca
zkanoca

Reputation: 9918

It is a classical JOIN operation:

SELECT 
        t1.id, t1.name, t2.comment 
FROM 
       Table1 AS t1 
LEFT JOIN 
       Table2 AS t2 ON t1.id = t2.uid  

Upvotes: 0

Alex
Alex

Reputation: 11579

select
table1.Id,
table1.Name,
table2.comment
from table1 left outer join table2 on table1.id=table2.Uid

Upvotes: 1

Related Questions