发布网友
共6个回答
热心网友
根据你的查询结果要求,可以根据一下几个步骤确定多表查询语句的写法:
1、要显示所有学生信息、班级、年级等信息,则需以主表1为主记录,其他表通过外连接的方式进行关联;
2、LEFT JOIN 关键字会从左表那里返回所有的行,即使在右表中没有匹配的行,确定主表之后,其他关联表使用LEFT JOIN;
3、拼接SQL语句,需要确定关联字段主表1与表2的关联为主表1.studentid=表2.studentid,
主表1与表3的关联为主表1.gradId=表3.gradId,主表1与表4的关联为主表1.classId=表4.classId
4、具体语句为:
SELECT 表1.ID, 表2.STUDENTNAME,表3.GRADNAME,表4.CLASSNAME
FROM 表1
LEFT JOIN 表2 ON 表1.STUDENTID = 表2.STUDENTID
LEFT JOIN 表3 ON 表1.GRADID = 表3.GRADID
LEFT JOIN 表4 ON 表1.CLASSID= 表4.CLASSID
热心网友
不知道你的表都叫什么名字,例如叫:table1\table2\table3\table4
select t1.id, t2.studentName, t3.gradName, t4.className
from table1 t1
join table2 t2 on t2.studentId = t1.studentId
join table3 t3 on t3.gradId = t1.gradId
join table4 t4 on t4.classId = t1.classId
热心网友
select 表1.id ,
表2.studentName,
表3.gradName,
表4.className
from 表1,表2,表3,表4
where 表1.studentId=表2.studentId
and 表1.gradId=表3.gradId
and 表1.classId=表4.classId
热心网友
左外连接好像是这样吧
select a.id, b.studentName, c.gradName, d.className
from 主表1 a
left join 表2 b on a.studentId = b.studentId
left join 表3 c on c.gradId = a.gradId
left join 表4 d on d.classId = a.classId
热心网友
select t1.id ,studentName,gradName ,className
from t1,t2,t3
where t1.studentId=t2.studentId
and t1.gradId=t3.gradId
and t1.classId=t4.classId
order by 1;
热心网友
select abc.id,abc.studentName,abc. gradName,d.className from
(select ab.id,ab.classId,ab.studentName,c. gradName from
(select a.id,a.gradId,b.studentName from 主表1 a left join 表2 b on a.studentId=b.studentId)ab
left jion 表3 c on ab.gradId = c.gradId) abc left jion 表4 d on abc.classId= d.classId