我很欣赏有许多教程和示例解释了JOIN概念 - 但是我很难将这些示例应用到我的特定场景中。我会很感激一些帮助,如果不是太多问题 - 分解解决方案中发生的事情以达到预期的效果。
3表:用户,评估,assessment_log。
用户
+--------+------+------+-----------+----------+-----------+-------+--------+-----------+---------------+------+----------+
| UserID | User | Pass | FirstName | LastName | LastLogin | Email | Mobile | Kenitalla | AccountStatus | Role | Operator |
+--------+------+------+-----------+----------+-----------+-------+--------+-----------+---------------+------+----------+
评估
+--------------+------+-----------+-----------+-----------+-----------+-----------+--------------+----------+---------+----------+
| AssessmentID | Name | Criteria1 | Criteria2 | Criteria3 | Criteria4 | Criteria5 | RoleRequired | Required | Renewal | Operator |
+--------------+------+-----------+-----------+-----------+-----------+-----------+--------------+----------+---------+----------+
assessment_logs
+-----------------+------+----------------+------------+--------+-----------+----------+----------+----------+----------+----------+----------+---------+---------------+---------+
| AssessmentLogID | Date | AssessmentName | AssessedBy | UserID | StaffName | Comments | Verdict1 | Verdict2 | Verdict3 | Verdict4 | Verdict5 | Verdict | RenewalPeriod | NextDue |
+-----------------+------+----------------+------------+--------+-----------+----------+----------+----------+----------+----------+----------+---------+---------------+---------+
当用户进行评估时,条目会进入assessment_log。某些评估是必需的(必填专栏中的真或假),其中一些是可选的。 RoleRequired列规定了评估所需的用户角色。
我想生成一个他们尚未通过的用户和评估列表。必须进行评估,并且所需角色必须与用户角色匹配。没有使用" Pass"进入assessment_log。在判决栏中表明评估尚未通过。
简单来说,我正在寻找一个能够达到以下结果的查询:
+------------------+-----------------+----------------+
| assessments.Name | users.FirstName | users.LastName |
+------------------+-----------------+----------------+
如果需要评估(必需等于true),则RequiredRole与users.Role列匹配,并且评估的assessment_log中没有条目,其中判决列包含" Pass"值。
如果需要进一步澄清,请告诉我。
提前致谢!
答案 0 :(得分:0)
我建议使用LEFT JOIN。
首先,我们生成评估和用户的交叉产品,其中包含每个用户所需的所有评估。
然后,LEFT JOIN会检查这些评估是否已通过。
SELECT ...
FROM
users u
JOIN assessments a ON (a.RoleRequired = u.Role)
LEFT JOIN assessment_logs al ON (
al.AssessmentID = a.AssessmentID
AND al.UserID = u.UserID
AND al.Verdict='Pass'
)
WHERE
a.required
AND al.UserID IS NULL
答案 1 :(得分:0)
您的属性名称在表格之间不一致,虽然我没有看到任何重复的名称,但这可能只是时间问题,所以我建议您解决此问题。
与此同时,以下是如何动态重命名列以简化连接语法:
SELECT AssessmentName, UserLastName, UserFirstName
FROM ( SELECT FirstName AS UserFirstName, Lastname AS UserLastName, Role
FROM users ) u
NATURAL JOIN
{ SELECT Name AS AssessmentName, RoleRequired AS Role
FROM assessments
WHERE Required ) a
NATURAL JOIN
( SELECT AssessmentName
FROM assessment_logs
WHERE Verdict = 'Pass' ) l;