两个表链接的问题
假如有一个表 ACCOUNT
ACCOUNTID, NAME, TYPE
A001, JOHN, TUTOR
A002, MIKE, TUTOR
A003, JIM, STUDENT
A004, LILY, STUDENT
另一个表 APPOINTMENT
STUDENTID, TUTORID
A003, A001
A004, A002
备注:STUDENTID和TUTORID都是ACCOUNTID的外键。
现在想得到student和tutor名字的对应列表,比如根据表APPOINTMENT和ACCOUNT,有如下结果
STUDENTNAME, TUTORNAME
JIM, JOHN
LILY, MIKE
不知道这个查询语句如何写,多谢指教。
[解决办法]
是这样吗:
create table ACCOUNT(ACCOUNTID varchar(10), NAME varchar(10), TYPE varchar(10))
insert into ACCOUNT
select 'A001', 'JOHN', 'TUTOR' union all
select 'A002', 'MIKE', 'TUTOR' union all
select 'A003', 'JIM', 'STUDENT' union all
select 'A004', 'LILY', 'STUDENT'
create table APPOINTMENT(STUDENTID varchar(10), TUTORID varchar(10))
insert into APPOINTMENT
select 'A003', 'A001' union all
select 'A004', 'A002'
go
select (select NAME from ACCOUNT a where a.ACCOUNTID = aa.STUDENTID) STUDENTNAME,
(select NAME from ACCOUNT a where a.ACCOUNTID = aa.TUTORID) TUTORNAME
from APPOINTMENT aa
/*
STUDENTNAMETUTORNAME
JIMJOHN
LILYMIKE
*/
create table ACCOUNT
(ACCOUNTID varchar(10),name varchar(10),TYPE varchar(10))
insert into ACCOUNT
select 'A001','JOHN','TUTOR' union all
select 'A002','MIKE','TUTOR' union all
select 'A003','JIM','STUDENT' union all
select 'A004','LILY','STUDENT'
create table APPOINTMENT
(STUDENTID varchar(10),TUTORID varchar(10))
insert into APPOINTMENT
select 'A003','A001' union all
select 'A004','A002'
select b.name 'STUDENTNAME',c.name 'TUTORNAME'
from APPOINTMENT a
left join ACCOUNT b on a.STUDENTID=b.ACCOUNTID
left join ACCOUNT c on a.TUTORID=c.ACCOUNTID
/*
STUDENTNAME TUTORNAME
----------- ----------
JIM JOHN
LILY MIKE
(2 row(s) affected)
*/