我有一个MySql数据库,我需要在查询中组合三个表:schedule,registered和waitlist。他们正在实施基本的课程注册系统。
计划包含计划的类。当用户注册课程时,他们的用户帐户ID和预定课程的ID将存储在已注册的课程中。如果一个类处于容量状态,则它们将存储在等待列表中。所有三个表共享一个scheduleId列,用于标识每个类。
当我查询计划表时,我还需要返回已注册和等待列表,这些列表示已注册并等待该特定scheduleId的用户数。
我想出的初步查询是:
select s.id, s.classDate, s.instructor, COUNT(e.id) as enrolled
from schedule as s
left outer join enrolled as e
on s.id = e.scheduleId
group by s.id
哪个适用于其中一个,但显然我无法通过这种方式获取已注册和等待列表的值。 任何人都可以建议这样做的好方法吗?
答案 0 :(得分:4)
使用嵌套的SELECT查询。假设你的架构有点像这样的东西(可能不适用于某些SQL版本):
select s.id, s.classDate, s.instructor,
(select COUNT(e.id) from enrolled e where e.scheduleId = s.id) as enrolled,
(select COUNT(w.id) from waitlist w where w.scheduleId = s.id) as waiting
from schedule as s
group by s.id
答案 1 :(得分:3)
我会使用另一个左连接和两个内联计数(区别)
select s.id, s.classDate, s.instructor ,
count(distinct e.id) as enrolled,
count(distinct w.id) as waiting
from schedule as s
left outer join enrolled as e
on s.id = e.scheduleID
left outer join waitlist as w
on s.id = w.scheduleID
group by s.id
当我运行这种方法而不是子查询时,它的执行速度提高了一倍,但我看的是一个非常小的结果集。
答案 2 :(得分:0)
两种快捷方式:
1-使用COUNT(DISTINCT e.id), COUNT(DISTINCT w.id)
获取每个表中的唯一实例数,然后加入两者。这可能是非常低效的。
2-在FROM
子句中使用子查询(仅适用于MySQL 5.0及更高版本):
SELECT s.id, s.classDate, s.instructor, tmpE.c AS enrolled, tmpW.c AS waiting
FROM
schedule AS s,
( SELECT scheduleID, COUNT(*) AS c FROM enrolled GROUP BY scheduleID ) AS tmpE,
( SELECT scheduleID, COUNT(*) AS c FROM waiting GROUP BY scheduleID ) AS tmpW
WHERE
s.id = e.scheduleID
AND s.id = w.scheduleID
GROUP BY s.id
我可能错过了那里的左联盟。