php - 从子查询进行查询

标签 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.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
}

由于您没有对物体进行水合处理,因此您应该会发现这种方法效果很好。

关于php - 从子查询进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46816801/

相关文章:

python MySQL : Lost connection to MySQL server during query

php - 可以读取cookie并在mysql SELECT 查询中使用

php - Symfony 1.4 - MySql View 的 getPager 附加变量

css - 从 form-symfony 为不同的文本字段提供不同的宽度

php - 如何使用 mysql 语法(如 if 条件)使用 codeigniter 表更新?

php - 停止远程服务器 PHP 上的无限循环

php - 根据下拉列表中选定的过滤器列出数据库值

php - PHP 中是否有像 C++ 那样的纯虚函数

mysql - SphinxSE 和 RT 索引相关的一些问题

php - Symfony session 值在特定服务器上丢失