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 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积