选择每个客户的姓名以及他们在会话中花费的总时间
我在 MySQL 数据库中设置了以下表:
Client:
id
name
Session:
id
service_id
date
Attendance:
id
client_id
session_id
Service:
id
duration
客户端通过出勤表与会话建立多对多关系。
我正在尝试编写一个查询,该查询将返回每个客户的姓名以及他们在会话中花费的总时间,如下所示:
Name Total Time (Mins)
Person A 200
Person B 500
Person C 100
到目前为止,我的查询如下所示:
SELECT
(SELECT SUM(services.duration)
FROM services
INNER JOIN sessions
ON sessions.service_id = services.id
INNER JOIN attendances
ON attendances.session_id = session.id
INNER JOIN clients
ON clients.id = attendances.client_id
GROUP BY clients.id) AS total_duration,
client.name
FROM clients
但是,这不会返回任何结果。然而,如果我单独运行查询的任何一部分,我都会得到我需要的数据,即:
SELECT name FROM clients
或者
SELECT SUM(services.duration)
FROM services
INNER JOIN sessions
ON sessions.service_id = services.id
INNER JOIN attendances
ON attendances.session_id = session.id
INNER JOIN clients
ON clients.id = attendances.client_id
GROUP BY clients.id
任何人都可以看到当我将两者结合起来时它不起作用的原因吗?
I have the following tables setup in a MySQL database:
Client:
id
name
Session:
id
service_id
date
Attendance:
id
client_id
session_id
Service:
id
duration
Clients have a many to many relationship with Sessions through the Attendance table.
I am trying to write a query which will return each clients' name and the total amount of time they have spent in sessions, like this:
Name Total Time (Mins)
Person A 200
Person B 500
Person C 100
So far my query looks like this:
SELECT
(SELECT SUM(services.duration)
FROM services
INNER JOIN sessions
ON sessions.service_id = services.id
INNER JOIN attendances
ON attendances.session_id = session.id
INNER JOIN clients
ON clients.id = attendances.client_id
GROUP BY clients.id) AS total_duration,
client.name
FROM clients
However, this returns no results. Whereas, if I run either part of the query in isolation I get the data I need, ie:
SELECT name FROM clients
OR
SELECT SUM(services.duration)
FROM services
INNER JOIN sessions
ON sessions.service_id = services.id
INNER JOIN attendances
ON attendances.session_id = session.id
INNER JOIN clients
ON clients.id = attendances.client_id
GROUP BY clients.id
Can anyone see a reason why it would not be working when I combine the two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在相关查询中缺少
WHERE
条件。我仅使用联接重写了您的查询,以使其更具可读性:You are missing a
WHERE
condition in correlated query. I rewrote your query with only joins to make it more readable: