doupao1530 2013-12-16 14:51
浏览 26
已采纳

结合这两个查询

I have 2 queries.

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

I've simplified the first query, I pass some arguments to the function to filter what events it returns, but that part isn't relevant to this question.

The problem I have if I want to get every event and it's items, it's doing a lot of queries (there are 691 events currently). Is there anyway I can combine these queries together?

  • 写回答

1条回答 默认 最新

  • doupu5941 2013-12-16 14:59
    关注

    You can JOIN the tables together to get the same answer. It should be a lot better performing, as well:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?