如何集成MySQL子查询

时间:2015-02-15 09:10:57

标签: mysql sql subquery

我有一个MySQL子查询,我需要将其纳入我的主要查询,但我不确定如何。我的主要查询如下所示。我想运行它,并作为相同查询的一部分运行子查询并从中获取结果(恰好是一个总和),然后在主MySQL语句中比较子查询的结果。

主要查询

select * from employees_timesheet where 
        (sign_off_1 = 'Director' or sign_off_2 = 'Director' or sign_off_3 = 'Director') 
        and
            (case when sign_off_1 <> 'Director' and sign_off_1_status = 'Compete' 
                then 1
                else 0
            end 
            + case when sign_off_2 <> 'Director' and sign_off_2_status = 'Compete' 
                then 1
                else 0
            end 
            + case when sign_off_3 <> 'Director' and sign_off_3_status = 'Compete' 
                then 1
                else 0
            end) = {{{$sign_offs_required}}}

子查询

select 
        SUM(
            case when employees_timesheet.sign_off_1 <> 'Director' 
                then 1
                else 0 
            end
            + case when employees_timesheet.sign_off_2 <> 'Director' 
                then 1
                else 0 
            end
            + case when employees_timesheet.sign_off_3 <> 'Director' 
                then 1
                else 0 
            end
        ) as sign_offs_required 
        from employees_timesheet

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我设法使用以下查询让它工作:

select et.* from employees_timesheet et where 
        (et.sign_off_1 = 'Director' or et.sign_off_2 = 'Director' or et.sign_off_3 = 'Director') 
        and
            (case when et.sign_off_1 <> 'Director' and et.sign_off_1_status = 'Approved' 
                then 1
                else 0
            end 
            + case when et.sign_off_2 <> 'Director' and et.sign_off_2_status = 'Approved' 
                then 1
                else 0
            end 
            + case when et.sign_off_3 <> 'Director' and et.sign_off_3_status = 'Approved' 
                then 1
                else 0
            end) = 
                (case when et.sign_off_1 <> 'Director' 
                        then 1
                        else 0 
                    end
                    + case when et.sign_off_2 <> 'Director' 
                        then 1
                        else 0 
                    end
                    + case when et.sign_off_3 <> 'Director' 
                        then 1
                        else 0 
                    end
                )
        group by et.id