有条件的加入Mysql select语句

时间:2010-02-03 12:39:01

标签: mysql conditional join

我有两张表tbl_studentapplicationdetailstbl_studentqualification ... 我的第二个表包含studentId和qualificationId ...现在我想加入两个表来获取具有资格的学生列表......

注意: 有些学生可能有两到三个资格......我的查询是

select distinct t1.dStudent_id,t1.dStuFirstname,t1.dStuLastName,t1.dGender,
t1.dFatherName,t1.dOcupation,
t1.dAddress,t1.dContactNumber,t2.dMarks as sslc,t3.dMarks as hsc,
t4.dMarks as diplomo from tbl_studentapplicationdetails as t1
inner join tbl_studentqualification as t2 on t2.dQualification = '1'
inner join tbl_studentqualification as t3 on t3.dQualification = '2'
left  join tbl_studentqualification as t4     on t4.dQualification = '7' 

我的tbl_studentqualification

alt text http://www.freeimagehosting.net/uploads/6e38525b5e.jpg

修改 我想为有两个资格的学生和有三个资格的学生选择所有记录....

2 个答案:

答案 0 :(得分:2)

截至目前,您的联接不太合理,因为您根本没有加入资格表中的应用程序详细信息。鉴于您希望学生ID不同,每个学生只能获得一行。

如果我理解了您想要的内容,您希望获得一个学生行中每种类型的资格(1,2,7)的信息。如果是这种情况,你应该尝试这样的事情(我希望这是正确的):

SELECT dStudent_id, dStuFirstname, dStuLastName, dGender,
       dFatherName, dOcupation, dAddress, dContactNumber,
       q1.dMarks as sslc, q2.dMarks as hsc, q7.dMarks as diplomo
FROM tbl_studentapplicationdetails
LEFT JOIN tbl_studentqualification as q1
    ON ( q1.dStudent_id = dStudent_id AND q1.dQualification = '1' )
LEFT JOIN tbl_studentqualification as q2
    ON ( q2.dStudent_id = dStudent_id AND q2.dQualification = '2' )
LEFT JOIN tbl_studentqualification as q7
    ON ( q7.dStudent_id = dStudent_id AND q7.dQualification = '7' )

答案 1 :(得分:0)