2013-12-16 191 views
0

我有2個問題。結合這2個查詢

public function fetchEvents(){ 

    $events = $this->cmsdb->query("SELECT * FROM tickets_events WHERE `active` = 1", true); //true just means if only one row is returned it will be key [0] so I can loop no matter how many rows returned 

if(empty($events)){ 
    return array(); 
    } 
    foreach ($events as $k => $event) { 
     $events[$k]['items'] = $this->cmsdb->query("SELECT *, FROM_UNIXTIME(date, '%W, %D %M %Y') as dateString 
           FROM tickets_items WHERE eventId = '" . intval($event['id']) . "' 
           AND public = 1 AND confirmed = 1 AND date > '" . time() . "' 
           ORDER BY date ", true); 
    } 
    return $events; 
} 

我已經簡化了第一個查詢,我通過一些函數的自變量來過濾返回結果是什麼事件,但是這部分是不相關的這個問題。

我遇到的問題是,如果我想要獲取每個事件和它的項目,它正在做很多查詢(目前有691個事件)。無論如何,我可以將這些查詢結合在一起嗎?

+0

爲什麼不在表之間建立一個'JOIN'並進行單個查詢? – Minoru

+0

我認爲這可能是問題所在 – Strawberry

回答

2

您可以將JOIN的表格一起得到相同的答案。它應該有更好的表現,以及:

SELECT 
    i.* 
    ,FROM_UNIXTIME(i.date, '%W, %D %M %Y') as dateString 
FROM tickets_items i 
JOIN tickets_events e 
    ON i.eventId = e.id 
WHERE i.public = 1 
    AND i.confirmed = 1 
    AND e.active = 1 
    AND date > CURRENT_TIMESTAMP 
ORDER BY date