mySQL将多个查询更改为单个查询

时间:2014-02-07 17:25:34

标签: mysql

我有两个mySQL表:

tblcoach:包含字段(coachid,coachschoolid,otherstuff)

tblschool:包含字段(schoolid,schooldivision)

我正在努力获得一份学校名单,这些名单仅限于那些与教练处于同一学位的学校。

这段代码我的工作原理,但是有时会产生一个mySQL查询来实现相同的结果吗?

SELECT @cs := coachschoolid FROM tblcoach c;
SELECT @sd := s.schooldivision FROM tblschool s WHERE s.schoolid = @cs;
SELECT s2.schoolid, s2.schoolname FROM tblschool s2 WHERE schooldivision = @sd

2 个答案:

答案 0 :(得分:0)

嵌套查询:

select schoolId, schoolname
from tblschool
where 
    schooldivision = (
        select schooldivision from tblschool where schoolid = (
            select coachschoolid from tblcoach
        )
    )

答案 1 :(得分:0)

这似乎只适用于1名教练。 您可以使用自联接来执行此操作:

SELECT s2.schoolid, s2.schoolname 
FROM tblschool s
INNER JOIN tblschool s2 on s.schooldivision = s2.schooldivision
WHERE s.schoolid = ? 

允许您传入schoolID。如果你想传入coachID:

SELECT s2.schoolid, s2.schoolname 
FROM tblschool s
INNER JOIN tblschool s2 on s.schooldivision = s2.schooldivision
INNER JOIN tblcoach c on c.coachschoolid = s.schoolid
WHERE c.coachid = ?