2012-05-03 2 views
0

이벤트를 포함하는 테이블이 있습니다. 이벤트 테이블을 반복하고, 이벤트 유형을 확인하고, 이벤트 ID가있는 특정 테이블을 조회합니다.mysql 쿼리와 하위 쿼리 결과를 하나의 PHP 배열로 결합합니다.

이 순간에 하나의 쿼리를 사용하여 20 개의 이벤트를 얻은 다음 최대 3 개의 쿼리를 사용하여 해당 이벤트의 데이터를 가져옵니다. 나는 현재 절차 적으로 코드화 해 놓았지만 결국에는 배열 형태로 데이터를 반환하도록 변경해야한다.

while(eventQuery): 

    if commentQueryResult; 
     $array .= commentQueryResult; 

    if forumPostQueryResult; 
     $array .= forumPostQueryResult; 

    if uploadItemQueryResult; 
     $array .= uploadItemQueryResult; 

endwhile; 

return $array; // Combined returned results as one array 

내가 다음을 통해 데이터와 단지 foreach는 루프에 액세스 할 수 있습니다 :

는 여기에 내가 달성하기 위해 필요한의 Pseduo 코드 예입니다.

여러 결과 집합을 배열로 결합하는 가장 좋은 방법은 확실하지 않습니까?

또는 당신이 시도하고 하나 개의 쿼리로 결합 할 수 ... 내가 PDO 이러한 모든 변환하는 과정에있어

$eventResult = mysql_query(
    'SELECT userevent.event, userevent.eventId, userevent.friendId 
    FROM userevent 
    WHERE userevent.userId = 1 OR userevent.friendId = 1 
    ORDER BY userevent.id DESC 
    LIMIT 20' 
); 

while ($eventRow = mysql_fetch_row($eventResult)){ 

    if($eventRow[0] == 1){ 

     $result = mysql_fetch_array(mysql_query(" 
      SELECT forumRooms.id, forumRooms.title                      
      FROM forumPosts             
      INNER JOIN forumRooms ON forumPosts.`forumTopic` = forumRooms.`id`              
      WHERE forumPosts.id = '$eventRow[1]'")); 
    } 
    elseif($eventRow[0] == 2){ 

     $result = mysql_fetch_array(mysql_query(" 
      SELECT game.id, game.uriTitle, game.title               
      FROM usergamecomment 
      INNER JOIN game ON usergamecomment.`gameId` = game.id 
      WHERE usergamecomment.id = $eventRow[1]")); 
    } 
    elseif($eventRow[0] == 4){ 

     $result = mysql_fetch_array(mysql_query(" 
      SELECT usercomment.comment, UNIX_TIMESTAMP(usercomment.TIME), `user`.id, `user`.username, `user`.activate 
      FROM usercomment 
      INNER JOIN `user` ON usercomment.`userId` = `user`.id 
      WHERE usercomment.id = $eventRow[1] 
      AND `user`.activate = 1")); 
    } 
    elseif($eventRow[0] == 5){ 

     $result = mysql_fetch_array(mysql_query(" 
      SELECT game.id, game.title, game.uriTitle 
      FROM game 
      WHERE game.id = $eventRow[1]")); 
    } 

// Combined Results as array 
} 

, 즉 가장 좋은 방법은 운동 후 다음 단계의 이것을 최소화하십시오.

+0

하나의 쿼리로 이벤트 목록과 이벤트 유형 테이블을 모두 쿼리 할 수 ​​있습니까? 'SELECT * FROM event e INNER JOIN eventType et on e.eventid = et.eventID' 당신의 질문을 오해했을 가능성이 있습니다. – andrewsi

+0

조인은 너무 복잡합니다. 다른 결과에서 반환 된 데이터 배열을 생성하기 위해 PHP를 사용하여 첫 번째 쿼리를 반복합니다. – Dan

+1

너무 복잡합니까? 나는 우리를 시험해 보라고 말할 것입니다. 적어도 나는 두뇌 티어를 좋아합니다. ;) – Paul

답변

1

챌린지 허용. ;)

사실 while 루프 내부의 결과에만 관심이 있으므로이 단일 쿼리를 시도해 볼 수 있습니다. LEFT JOINS로 인해 데이터베이스가 더 빠를 수도 있습니다. 최종 $result에는 해당 필드가있는 모든 요소가 들어 있습니다.

$result = array(); 
$q = 'SELECT userevent.event AS userevent_event, 
     userevent.eventId AS userevent_eventId, 
     userevent.friendId AS userevent_friendId, 
     forumRooms.id AS forumRooms_id, 
     forumRooms.title AS forumRooms_title, 
     game.id AS game_id, 
     game.uriTitle AS game_uriTitle, 
     game.title AS game_title, 
     usercomment.comment AS usercomment_comment, 
     UNIX_TIMESTAMP(usercomment.TIME) AS usercomment_time, 
     user.id AS user_id, 
     user.username AS user_username, 
     user.activate AS user_activate, 
     g2.id AS game2_id, 
     g2.uriTitle AS game2_uriTitle, 
     g2.title AS game2_title 


    FROM userevent 
    LEFT JOIN forumPosts ON forumPosts.id = userevent.eventId 
    LEFT JOIN forumRooms ON forumPosts.forumTopic = forumRooms.id 
    LEFT JOIN usergamecomment ON usergamecomment.id = userevent.eventId 
    LEFT JOIN game ON usergamecomment.gameId = game.id 
    LEFT JOIN usercomment ON usercomment.id = userevent.eventId 
    LEFT JOIN user ON usercomment.userId = user.id 
    LEFT JOIN game g2 ON userevent.eventId = g2.id 
    WHERE (userevent.userId = 1 OR userevent.friendId = 1) 
     AND userevent.eventId >= (SELECT userevent.eventId 
       WHERE userevent.userId = 1 OR userevent.friendId = 1 
       ORDER BY userevent.id DESC LIMIT 1,20);'; 

$r = mysql_query($q); 

while ($o = mysql_fetch_row($r)) { 
    switch($o['userevent_event']) { 
    case 1: 
     $result[] = array(
    'id' => $o['forumsRooms_id'], 
    'title' => $o['forumsRooms_title'], 
    ); 
     break; 
    case 2: 
     $result[] = array(
    'id' => $o['game_id'], 
    'uriTitle' => $o['game_uriTitle'], 
    'title' => $o['game_title'], 
    ); 
     break; 
    case 4: 
     $result[] = array(
    'comment' => $o['usercomment_comment'], 
    'time' => $o['usercomment_time'], 
    'id' => $o['user_id'], 
    'username' => $o['user_username'], 
    'activate' => $o['user_activate'], 
    ); 
     break; 
    case 5: 
     $result[] = array(
    'id' => $o['game2_id'], 
    'uriTitle' => $o['game2_uriTitle'], 
    'title' => $o['game2_title'], 
    ); 
     break; 
    } 
} 

참고 : 궁극적으로 쿼리를 약간 편집해야합니다. 단지 머리를 쓰지 않고 테스트 한 것입니다. DB 구조에 대해 더 많이 알고 있다면 최적화가 확실하게 수행 될 수 있습니다.

또한 이것은 단일 쿼리로 실제로 수행 될 수 있다는 개념의 증명 일뿐입니다. ;)

+0

매우 인상적입니다! 따라서 20 개의 쿼리가 제거되고 실행하는 데 0.7 초 밖에 걸리지 않으므로 외래 키가 잘 작동해야합니다. – Dan

+0

잘 알고 있습니다. 언제든지 환영합니다. ;) – Paul

관련 문제