duancan9815 2011-07-14 10:09
浏览 19
已采纳

Doctrine中的条件连接?

I've two tables, location and forecast. I'd like to query the database to find all locations that match forecast parameters for each day.

e.g. London has forecast entries for the days 2011-07-13, 2011-07-14, 2011-07-15, and 2011-07-16. I'd like London to be returned if on 2011-07-14 AND 2011-07-15 the temperature is not higher than 40 and not lower than 13.

I've managed to work this out in MySQL (I think):

SELECT f1.day, f1.temperature_high, f1.temperature_low, f2.day, f2.temperature_high, f2.temperature_low, l.name 
FROM location l
INNER JOIN forecast f1 ON 
  f1.location_id = l.id AND 
  f1.day = '2011-07-14' AND 
  f1.temperature_high <= '40' AND 
  f1.temperature_low >= '13'
INNER JOIN forecast f2 ON 
  f2.location_id = l.id AND 
  f2.day = '2011-07-15' AND 
  f2.temperature_high <= '40' AND 
  f2.temperature_low >= '13';

I attempted to translate this into Doctrine, but I'm getting memory exhausted errors. My Doctrine query:

$this->results = Doctrine_Query::create()->select('l.name')->from('Location l');

foreach ($values['day'] as $i => $day) { $this->results->innerJoin('l.Forecasts f'.$i.' ON f'.$i.'.condition_id IN (' . implode(',', $values['condition']) . ') AND f'.$i.'.temperature_high <= ' .$values['temperature_max'] . ' AND f'.$i.'.temperature_low >= ' . $values['temperature_min']); } $this->results->execute();

What is the correct & most efficient way of running this query? I'm pretty sure I'm doing something fundamentally wrong.

Many thanks in advance
Pete

  • 写回答

1条回答 默认 最新

  • duangouhui0446 2011-07-14 10:26
    关注

    I think it would be easier to use $query->addWhere('EXISTS (...)') with an inner select statement for each condition.

    $this->results = Doctrine_Query::create()->select('name')->from('location');
    
    foreach ($values['day'] as $i => $day) {
        $this->results->addWhere('EXISTS (
            SELECT NULL
            FROM forecast
            WHERE location_id = location.id
            AND condition_id IN (' . implode(',', $values['condition']) . ')
            AND temperature_high <= ' . $values['temperature_max'] . '
            AND temperature_low >= ' . $values['temperature_min'] . '
        )');
    }
    $this->results->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)