1

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.

4

3 に答える 3

4

使用left joinしてみると、からのすべてのデータが表示されますtable1

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

:

上記のようにエイリアスを使用することをお勧めします。コードがより読みやすくなります。

于 2013-08-01T06:57:24.160 に答える
0

これは古典的なJOIN操作です。

SELECT 
        t1.id, t1.name, t2.comment 
FROM 
       Table1 AS t1 
LEFT JOIN 
       Table2 AS t2 ON t1.id = t2.uid  
于 2013-08-01T06:57:16.357 に答える