背景
我有两张表,在 MySQL 中有不同类型的反馈项。我已经构建了一个查询来组合这些表FULL OUTER JOIN
(实际上在 MySQL 中写为两个连接和一个联合)并计算一些平均成绩。这个查询似乎完美地工作:
(SELECT name, AVG(l.overallQuality) AS avgLingQual,
AVG(s.overallSatisfaction) AS avgSvcQual
FROM feedback_linguistic AS l
LEFT JOIN feedback_service AS s USING(name)
GROUP BY name)
UNION ALL
(SELECT name, AVG(l.overallQuality) AS avgLingQual,
AVG(s.overallSatisfaction) AS avgSvcQual
FROM feedback_linguistic AS l
RIGHT JOIN feedback_service AS s USING(name)
WHERE l.id IS NULL
GROUP BY name)
ORDER BY name;
(这在某种程度上简化了可读性,但在这里没有什么区别)
问题
接下来我尝试添加按日期过滤(即只考虑在某个日期之后创建的反馈项)。凭借我的 SQL 技能和我所做的研究,我能够想出这个:
(SELECT name, AVG(l.overallQuality) AS avgLingQual,
AVG(s.overallSatisfaction) AS avgSvcQual
FROM feedback_linguistic AS l
LEFT JOIN feedback_service AS s USING(name)
WHERE (s.createdTime >= '" & date & "' OR s.createdTime IS NULL)
AND (l.createdTime >= '" & date & "' OR l.createdTime IS NULL)
GROUP BY name)
UNION ALL
(SELECT name, AVG(l.overallQuality) AS avgLingQual,
AVG(s.overallSatisfaction) AS avgSvcQual
FROM feedback_linguistic AS l
RIGHT JOIN feedback_service AS s USING(name)
WHERE l.id IS NULL
AND (s.createdTime >= '" & date & "' OR s.createdTime IS NULL)
GROUP BY name)
ORDER BY name;
这几乎可行:我得到的结果看起来是正确的。但是,缺少一些反馈项。例如,设置一个月前的日期,我在数据库中统计了 21 个人的反馈,但这个查询只返回 19 个人。最糟糕的是,我似乎找不到丢失的物品之间的任何相似之处。
我在这个查询中做错了吗?我认为该WHERE
子句在 the 之后进行日期过滤JOIN
,理想情况下我可能会在此之前进行。再说一次,我不知道这是否会导致我的问题,而且我也不知道如何以不同的方式编写此查询。