我在MySQL数据库中设置了以下表格:
Client:
id
name
Session:
id
service_id
date
Attendance:
id
client_id
session_id
Service:
id
duration
客户通过出席表与Sessions建立了多对多的关系。
我正在尝试编写一个查询,它将返回每个客户的名字以及他们在会话中花费的总时间,例如:
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
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
当我把两者结合起来时,有人能看出为什么它不起作用的原因吗?
答案 0 :(得分:1)
您在相关查询中缺少WHERE
条件。我只使用连接重写了您的查询,以使其更具可读性:
SELECT c.name, sum(srv.duration)
FROM clients c
JOIN attendances a ON a.client_id = c.id
JOIN sessions s ON s.id - a.session_id
JOIN services srv ON srv.id = s.service_id
GROUP BY c.name