2011-07-14 40 views
0

我有兩個表,位置和預測。我想要查詢數據庫以查找與每天的預測參數相匹配的所有地點。條件的學說加入?

例如倫敦預測2011-07-13,2011-07-14,2011-07-15和2011-07-16的日子。我想返回倫敦,如果對2011-07-14和2011-07-15溫度不高於40℃,不低於13

我已經成功在MySQL中工作了這一點(我認爲):

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';

我試圖把它翻譯成教義,但我得到內存耗盡的錯誤。我的學說查詢:

$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();

什麼是正確&運行此查詢的最有效方式?我很確定我正在做一些根本性錯誤的事情。

提前感謝
皮特

回答

2

我認爲這將是更容易使用$query->addWhere('EXISTS (...)')爲每個條件的內SELECT語句。

$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(); 
+0

由於EXISTS正常工作 –

+0

如何將其更改爲Doctrine 2? –

+0

@OlegAbrazhaev看一看[查詢與存在學說的Symfony2](/ Q/10030538) –