求SQL查询语句,一个表为主表,包含另外1个表的2个字段,根据用户ID主表记录全部显示,同时要根据另外1个表的2个字段来显示信息。如主表字段如下
table1:
id name a1 a2
1 语文 11 12
2 数学 21 22
3 英语 31 32
4 物理 41 42
5 化学 51 52
table2:一条记录只记录a1或a2的值,也就是其中总有一个为0
id uid a1 a2
1 1 11 0
2 1 0 22
3 1 0 12
4 1 41 0
5 1 51 0
6 1 0 42
7 2 0 52
要显示如下结果:根据uid=1,table1的记录全部显示,如果table2中有a1或a2就显示值,否则值为0
id uid name a1 a2
1 1 语文 11 12
2 1 数学 0 22
3 1 英语 0 0
4 1 物理 41 42
5 1 化学 51 0
使用left join
declare @table1 table ( id int not null, name nvarchar(10) not null, a1 int not null, a2 int not null ) declare @table2 table ( id int not null, uid int not null, a1 int not null, a2 int not null ) insert into @table1 values(1,N'yuwen',11,12), (2,N'shuxue',21,22), (3,N'yingyu',31,32), (4,'wuli',41,42), (5,'huaxue',51,52) insert into @table2 values(1,1,11,0), (2,1,0,22), (3,1,0,12), (4,1,41,0), (5,1,51,0), (6,1,0,42), (7,2,0,52) select t1.id, t2.uid, t1.name, case when t1.a1=t2.a1 then t1.a1 when t2.a2=t1.a2 then t2.a1 else 0 end as a1, case when t1.a1=t2.a1 then t1.a2 when t2.a2=t1.a2 then t2.a2 else 0 end as a1 from @table1 t1 left join @table2 t2 on t2.id=t1.id and t2.uid=1
根据用户ID主表记录全部显示,要显示主表所有的内容你就需要左连接,把主表放在左边主位置,select A.id,B.uid,A.name,isnull(A.a1,0),isnull(A.a2,0) from table1 as A LEFT JOIN table2 as B on A.id=B.uid;不知道能不帮助你希望可以;