dua55014 2014-05-23 08:55
浏览 119
已采纳

如何在CakePHP中编写带子查询的Select

I have the following query:

$queryResult = $this->Hit->query(
    "select P, count(S) as S
    from 
    (
        select pattern_id as P, srn as S from hits 
        where job_id=".$id." and srn != ''
        group by srn, pattern_id 
        order by pattern_id, srn
    ) as T 
        group by P
        order by P;"
);

So basically I have a select .. from (select .. ) ... statement. It's working perfect while I'm using MySQL. But I have to migrate the DB to PostgreSQL so I would like to change this to the Cake-way. So my question is, how can I interpret this type of query (select from select) in CakePHP?

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dpqy77560 2014-05-23 11:24
    关注

    I am not sure what you mean by interpret this query in CakePHP since your code is valid CakePHP.

    That being said, I would rewrite your query as:

    SELECT pattern_id as P, COUNT(DISTINCT srn) as S
    FROM hits
    WHERE job_id=".$id." and srn != ''
    GROUP BY pattern_id
    ORDER BY pattern_id;
    

    (I believe this is equivalent - you could load sqlfiddle.com with sample data for better testing)

    If that works and you have a Hits model, then you could re-write the query using the find method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?