Php 从子查询进行查询

Php 从子查询进行查询,php,mysql,symfony-1.4,doctrine-1.2,Php,Mysql,Symfony 1.4,Doctrine 1.2,我正在尝试将以下sql查询传递给Doctrine: SELECT id, name, count(*) FROM (SELECT r.id, r.name, f.timestamp FROM `food_log` as f inner join recipe as r on f.recipe_id = r.id WHERE f.user_id = 6 and timestamp > "2016-09-01" and recipe_id is not null group by f.time

我正在尝试将以下sql查询传递给Doctrine:

SELECT id, name, count(*) FROM (SELECT r.id, r.name, f.timestamp FROM `food_log` as f inner join recipe as r on f.recipe_id = r.id WHERE f.user_id = 6 and timestamp > "2016-09-01" and recipe_id is not null group by f.timestamp, r.id) a GROUP BY a.id ORDER BY count(*) DESC
它应该返回给我食谱,其中包含特定用户从所选时间戳中使用单个食谱的次数

现在我正试图用Doctrine 1.2和Symfony 1.4实现这一点,但是我不知道如何从子查询中进行查询,我正在尝试这样做

        $subQuery = Doctrine_Query::create()
        ->select('r.id, r.name, f.timestamp')
        ->from('FoodLog f')
        ->innerJoin('f.Recipe r')
        ->where('f.user_id = ?', $userId)
        ->andWhere('timestamp > ?', "2016-09-01")
        ->andWhere('f.recipe_id is not null')
        ->andWhere('r.is_premium = ?', $premium)
        ->groupBy('f.timestamp, r.id')
        ->getSqlQuery();

    $query = Doctrine_Query::create()
    ->select('id, name, count(*)')
    ->from($subQuery)
    ->groupBy('id')
    ->orderBy('count(*) DESC');

    return $query->fetchArray();
有人知道我错在哪里吗?
非常感谢您的回复

基本上,在这个版本的条令中不能进行嵌套查询。我建议通过doctrine连接器使用原始SQL查询:

$sql = 'SELECT id, name, count(*) FROM (SELECT r.id, r.name, f.timestamp FROM `food_log` as f inner join recipe as r on f.recipe_id = r.id WHERE f.user_id = 6 and timestamp > "2016-09-01" and recipe_id is not null group by f.timestamp, r.id) a GROUP BY a.id ORDER BY count(*) 
DESC';
$conn = Doctrine_Manager::getInstance()->getCurrentConnection();
$result = $conn->execute($sql);

foreach($result as $data){
    // do something
}

由于您没有水合对象,您应该会发现这很有效。

基本上,您不能在这个版本的条令中进行嵌套查询。我建议通过doctrine连接器使用原始SQL查询:

$sql = 'SELECT id, name, count(*) FROM (SELECT r.id, r.name, f.timestamp FROM `food_log` as f inner join recipe as r on f.recipe_id = r.id WHERE f.user_id = 6 and timestamp > "2016-09-01" and recipe_id is not null group by f.timestamp, r.id) a GROUP BY a.id ORDER BY count(*) 
DESC';
$conn = Doctrine_Manager::getInstance()->getCurrentConnection();
$result = $conn->execute($sql);

foreach($result as $data){
    // do something
}

由于您不是在给物品补水,您应该会发现这很有效。

谢谢!它帮助了汉克斯!它有助于代替执行两个groupby,可以执行
计数(不同时间戳)
并保存额外的子查询。代替执行两个groupby,可以执行
计数(不同时间戳)
并保存额外的子查询。