如何在mysql中合并多个连接(给出的示例查询)

时间:2015-06-25 19:17:50

标签: mysql mysql-workbench

我需要为多名学生重复下面的连接。如何优化并将其作为单个查询编写?

select * from marks mar
join subject subj ON mar.subject_id=subj.subject_id
join student std ON subj.student_id = std.sutdent_id
Where std.student_name="xyz" and std.location="abc" and age="18"

select * from marks mar
join subject subj ON mar.subject_id=subj.subject_id
join student std ON subj.student_id = std.sutdent_id
Where std.student_name="ccc" and std.location="kkk" and age="19"

2 个答案:

答案 0 :(得分:1)

是......

select * from marks mar
join subject subj ON mar.subject_id=subj.subject_id
join student std ON subj.student_id = std.sutdent_id
Where 
    (std.student_name="xyz" and std.location="abc" and age="18")
    OR
    (std.student_name="ccc" and std.location="kkk" and age="19")

......过度简化了吗?

答案 1 :(得分:1)

这将解析MySQL:

SELECT  *
FROM    marks mar
JOIN    subject subj
ON      subj.subject_id = mar.subject_id
JOIN    student std
ON      std.student_id = subj.student_id
WHERE   (std.student_name, std.location, age) IN (('xyz', 'abc', 18), ('ccc', 'kkk', 19))

但不提供更好的执行计划。

或者,使用此:

SELECT  *
FROM    marks mar
JOIN    subject subj
ON      subj.subject_id = mar.subject_id
JOIN    student std
ON      std.student_id = subj.student_id
WHERE   (std.student_name, std.location, age) = ('xyz', 'abc', 18)
        OR
        (std.student_name, std.location, age) = ('ccc', 'kkk', 19)