使用子查询转换SQL语句

时间:2013-02-09 14:49:11

标签: php zend-framework

我正在使用Zend Framework开发一个网站。后端数据库是MySQL。当我将其复制并粘贴到phpMyAdmin时,以下SQL执行时没有任何错误。但是,我无法使用多个子查询转换此类SQL,因此可以在Zend Framework之上运行。

update 
    tb_data_proposal_crpf_reviewer
set
    is_commented = 0
where
    id IN (
    select 
        t.id
    from
        (
        select
            r.id as id
        from
            tb_data_proposal_crpf_reviewer r
            left join tb_data_panel_member m on m.id = r.panel_member_id
        where
            r.proposal_crpf_id = :crpf_id and
            r.is_commented = 1 and
            m.panel_code IN (
                select
                    distinct(s.panel_code)
                from
                    tb_data_proposal_crpf_stage s
                where
                    s.proposal_crpf_id = :crpf_id and
                    s.crp_stage_code = 1
            )
        ) as t
)

3 个答案:

答案 0 :(得分:0)

所有子查询都需要有别名,因此请尝试更新:

    where
        s.proposal_crpf_id = :crpf_id and
        s.crp_stage_code = 1
)

    where
        s.proposal_crpf_id = :crpf_id and
        s.crp_stage_code = 1
) as u
  ^^^^

答案 1 :(得分:0)

如果第一个查询给出与第二个查询相同的结果,则可以将逻辑拆分为首先加载所有受影响的ID,然后通过常用的Zend方法对其进行更新。

不幸的是,我无法验证第一个查询。

第一

select
  distinct(r.id) as id
from
  tb_data_proposal_crpf_reviewer AS r
  left join tb_data_panel_member AS m
    on
      m.id = r.panel_member_id
        and
      m.panel_code = r.panel_code
where
  r.proposal_crpf_id = :crpf_id
    and
  r.is_commented = 1
    and
  r.crp_stage_code = 1

第二

select
    r.id as id
from
    tb_data_proposal_crpf_reviewer r
    left join tb_data_panel_member m on m.id = r.panel_member_id
where
    r.proposal_crpf_id = :crpf_id and
    r.is_commented = 1 and
    m.panel_code IN (
        select
            distinct(s.panel_code)
        from
            tb_data_proposal_crpf_stage s
        where
            s.proposal_crpf_id = :crpf_id and
            s.crp_stage_code = 1
    )
) as t

答案 2 :(得分:0)

在这里看看mindlock的答案,它对我使用子查询起作用,希望它对你也有帮助

zend-framework-zend-db-select-how-to-join-custom-subquery-table