如何在第三个表的查询中包含来自其他两个表的筛选行计数?
我有一个 MySql 数据库,其中包含三个表,我需要在查询中组合这些表:计划表、注册表和候补表。 他们正在实施基础班招生制度。
时间表包含预定的课程。 当用户注册课程时,他们的用户帐户 ID 和预定课程的 ID 会存储在 enrolled 中。 如果班级已满,则会将其存储在候补名单中。 所有三个表共享一个用于标识每个类别的 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
这对于其中一个或另一个都可以正常工作,但显然我无法通过这种方式获取已注册表和候补表的值。 有人能建议一个好方法吗?
I have a MySql database with three tables I need to combine in a query: schedule, enrolled and waitlist. They are implementing a basic class enrollment system.
Schedule contains the scheduled classes. When a user enrolls in a class, their user account id and the id of the scheduled class are stored in enrolled. If a class is at capacity, they are stored in waitlist instead. All three tables share a scheduleId column which identifies each class.
When I query the schedule table, I need to also return enrolled and waitlist columns that represent the number of users enrolled and waiting for that particular scheduleId.
A preliminary query I came up with to accomplish this was:
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
which works ok for one or the other, but obviously I can't get the values for both the enrolled and waitlist tables this way.
Can anybody suggest a good way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用嵌套 SELECT 查询。 假设一些关于你的模式,像这样的东西怎么样(可能不适用于某些 SQL 风格):
Use nested SELECT queries. Assuming a bit about your schema, how about something like this (might not work on some flavors of SQL):
我会用另一个左连接和两个内联计数(不同)来实现
当我运行这种方法与子查询相比时,它的执行速度大约是其两倍,但我正在查看一个非常小的结果集。
I would do it with another left join and two inline count(distincts)
When I ran this approach versus the subqueries it executed about twice as fast, but I am looking at a pretty small result set.
两种快速方法:
1- 使用
COUNT(DISTINCT e.id), COUNT(DISTINCT w.id)
获取每个表中唯一实例的数量,然后连接两个表。 这可能是极其低效的。2-在
FROM
子句中使用子查询(仅适用于MySQL 5.0及更高版本):不过,我可能错过了其中的左连接。
Two quick ways:
1- Use
COUNT(DISTINCT e.id), COUNT(DISTINCT w.id)
to get the number of unique instances in each table, then join on both. This is possibly hideously inefficient.2- Use subqueries in the
FROM
clause (only works in MySQL 5.0 and later):I may have missed a left join in there, though.