从WHERE条件内的子查询求和

时间:2017-01-03 19:19:25

标签: mysql sql

您好我想知道如何访问子查询的结果并将其用作主查询中的条件

以下是我的查询代码:

SELECT m.*, dp.department as dep, 
(SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `time` ) ) ) FROM time_management tm WHERE tm.user = m.id AND MONTH(`date`) = MONTH(CURRENT_DATE()) AND YEAR(`date`)= YEAR(CURRENT_DATE()) ) as time
FROM members m 
LEFT JOIN department dp ON m.department = dp.id 
WHERE m.department = $departmentvar AND tm.time > 34

正如您所看到的,我正在尝试在WHERE子句时间中使用最后一个条件来仅选择SUM大于34的结果。

是否可以使用子查询?

欢迎任何帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

MySQL扩展了HAVING子句的使用,因此您可以将查询编写为:

SELECT m.*, dp.department as dep, 
       (SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `time` ) ) )
        FROM time_management tm
        WHERE tm.user = m.id AND
              MONTH(`date`) = MONTH(CURRENT_DATE()) AND
              YEAR(`date`) = YEAR(CURRENT_DATE())
       ) as time
FROM members m LEFT JOIN
     department dp
     ON m.department = dp.id 
WHERE m.department = $departmentvar 
HAVING time > 34;

time子句中的HAVING应解释为SELECT中定义的别名。

在大多数其他数据库中,您将使用子查询。但是,MySQL实现了子查询,这会产生额外的开销。

此外,我不认为此处需要LEFT JOIN - 除非您的部门不在departments表中。