select id,name,(select nvl(Score,0) from Table2 where id=a.id) from table1 a
nvl(t2.score,0)==>如果t2.score为空则输出0否则输出t2.score from table1 t1, table2 t2 where t1.id=t2.id(+)==>table1表与table2表做左外连接(根据table1.id和table2.id),也就是说table1表中取所有记录,table2表是对应id字段的值的记录,如果table2表中没有对应id值的记录,则为空。
也可以写一个view啊!很方便!create or replace view a as ( select A.ID,A.Name,B.Score from Table1 A,Table2 B where A.ID = B.ID ); select * from a;
from table1 t1, table2 t2 where t1.id=t2.id(+)==>table1表与table2表做左外连接(根据table1.id和table2.id),也就是说table1表中取所有记录,table2表是对应id字段的值的记录,如果table2表中没有对应id值的记录,则为空。
select A.ID,A.Name,B.Score
from Table1 A,Table2 B
where A.ID = B.ID
);
select * from a;
象他这样写sql是不好的,因为,对于数据库来说,这条语句是一个两层的查询语句。
而建立视图不必要,因为你取的字段和表关联都很少,虽然没有必要去建立视图
同时,我想你这个问题主要是在于一个外关联和内关联的问题bobfang(匆匆过客) 已经说的够详细了
from table1 a,table2 b
where a.id=b.id(+)
order a.id
贝克汉姆的做法非常准确,效率也比bobfang的要高
而且也比较直观!