如何从蛋糕php(蛋糕2)中的两个表中选择记录

时间:2015-07-10 12:55:11

标签: php mysql cakephp

我是新蛋糕php。我有两张桌子

  1. ce_landing
  2. ce_stat
  3. 结构是

    ce_stat

    id       keyword       click
    1        keyword1       24
    2        keyword2       2
    3        keyword3       6
    

    ce_landing

    id       page_keyword
    1        keyword1,check,keyword3
    2        keyword2,usa,alphanumeric
    

    我想获取ce_landing.page_keyword中存在的所有记录ce_stat.keyword。我在我的蛋糕php模型中使用它

     public $hasMany = array(
            'Stat' => array(
                'className' => 'Stat',
                'foreignKey' => 'keywor',
                'dependent' => false,
                'conditions' => array('Stat.keyword LIKE' => '%Landing.page_keywords%'),
                'group' => '',
                'order' => '',
                'limit' => '',
                'offset' => '',
                'exclusive' => '',
                'finderQuery' => '',
                'counterQuery' => ''
            )
            );
    

    但这是生成的SQL查询,如

      

    SQL查询:SELECT StatidStatcustomer_idStataccount,   Statcampaign_idStatcampaignStatkeyword,   Statad_grp_idStatad_grpStatimpressions,   StatclicksStatcostStatqualityScore,   StatkeywordStateStatdate_fromStatdate_to,   Statuser_idStatcreatedStatmodifiedStatkeywor   FROM EB_adwordsce_stats AS Stat WHERE Statkeyword LIKE   '%Landing.page_keywords%'和Statkeyword =   ( '559f479a-82ac-4e3d-8c24-19b5c0a8011f')

    因为AND Statkeyword =('559f479a-82ac-4e3d-8c24-19b5c0a8011f')条件,它返回空数据。

    更新

    根据目前的关键字,我希望获得ce_landing的所有记录的总点击次数。即ce_landing中的记录1。我会得到结果

    id       page_keyword                     clicks
        1        keyword1,check,keyword3        30
        2        keyword2,usa,alphanumeric       2
    

1 个答案:

答案 0 :(得分:1)

您需要一个等同于:

的SQL语句
SELECT ce_landing.id, ce_landing.page_keyword, SUM(ce_stat.click) AS total_clicks
FROM ce_landing
LEFT JOIN ce_stat
 ON FIND_IN_SET(keyword,page_keyword)>0
GROUP BY ce_landing.id, ce_landing.page_keyword;

不容易转换为Cakephp的find方法。只需使用query method即可实现。

$this->Landing->query("SELECT Landing.id, Landing.page_keyword, SUM(ce_stat.click) AS total_clicks
    FROM ce_landing AS Landing
    LEFT JOIN ce_stat
     ON FIND_IN_SET(keyword,page_keyword)>0
    GROUP BY Landing.id, Landing.page_keyword;");