我想在一个键上将多个结果集连接到1个结果。
有3个表(我在这里只添加相关记录):
Project table : | id | project |
File table : | id | project_id |
Approved table: | file_id | dep1_date | dep2_date | dep3_date |
部门默认是日期字符串:0000-00-00 00:00:00 第一个查询是:
SELECT project.project,
SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(approved.dep1_date,file.uploaded_datetime)))) as dep1_avg
FROM APPROVED
LEFT JOIN file on file.id = approved.file_id
LEFT JOIN project on project.id=file.project_id
WHERE approved.dep1_date != '0000-00-00 00:00:00'
GROUP BY project.project
它会给我平均分组的批准时间等项目:
Project Dep1_avg
project1 01:03:02
project2 04:14:03
project3 00:07:56
...
我想用dep2和dep3_date再次运行此查询2次,并附加到第一个结果集,但包含不同的WHERE statament(approved.dep2_date,approved.dep3_date)。
如何查看表格?
Project Dep1_avg Dep2_avg Dep3_avg
project1 01:03:02 04:23:11
project2 04:14:03 11:33:44
project3 00:07:56 00:13:43 32:24:17
...
另外2个结果与第一个查询(通过项目)相同,如果没有对某个项目的批准,则Dep2或Dep3将其分为NULL或空
查询的内容是什么?
由于
答案 0 :(得分:1)
您不应该使用多个where语句,而是选择是否在select本身内的AVG中包含一行。 (通过执行多个子查询,可以完成多个where语句,但这可能效率不高。
SELECT project.project,
SEC_TO_TIME(AVG(IF( approved.dep1_date != '0000-00-00 00:00:00', TIME_TO_SEC(TIMEDIFF(approved.dep1_date,file.uploaded_datetime), NULL))) as dep1_avg
SEC_TO_TIME(AVG(IF( approved.dep2_date != '0000-00-00 00:00:00', TIME_TO_SEC(TIMEDIFF(approved.dep2_date,file.uploaded_datetime), NULL))) as dep2_avg
SEC_TO_TIME(AVG(IF( approved.dep3_date != '0000-00-00 00:00:00', TIME_TO_SEC(TIMEDIFF(approved.dep3_date,file.uploaded_datetime), NULL))) as dep3_avg
FROM APPROVED
LEFT JOIN file on file.id = approved.file_id
LEFT JOIN project on project.id=file.project_id
GROUP BY project.project
为NULL的值不包含在diff中,因此这基本上只是检查是否应该包含该值,并且在这种情况下将其交换为NULL,这将被忽略。这使您可以废弃整个WHERE子句。
答案 1 :(得分:0)
试试这个:
SELECT project.project,
SEC_TO_TIME(AVG(TIME_TO_SEC(IF(approved.dep1_date != '0000-00-00 00:00:00', TIMEDIFF(a.dep1_date, f.uploaded_datetime), NULL)))) AS dep1_avg,
SEC_TO_TIME(AVG(TIME_TO_SEC(IF(approved.dep2_date != '0000-00-00 00:00:00', TIMEDIFF(a.dep2_date, f.uploaded_datetime), NULL)))) AS dep2_avg,
SEC_TO_TIME(AVG(TIME_TO_SEC(IF(approved.dep3_date != '0000-00-00 00:00:00', TIMEDIFF(a.dep3_date, f.uploaded_datetime), NULL)))) AS dep3_avg
FROM APPROVED a
LEFT JOIN `file` f ON f.id = a.file_id
LEFT JOIN project p ON p.id = f.project_id
GROUP BY p.project;