我有一個包含事件的表,要列出這些事件,我循環瀏覽事件表,檢查事件類型並使用它的eventId查找它的特定表中的值。將mysql查詢與子查詢結果合併到一個PHP數組中
目前,這使用一個查詢來獲取20個事件,然後最多3個查詢來獲取這些事件的數據。我目前使用程序編碼,但需要對其進行更改,以便在最後它僅以數組形式返回數據。
這裏是什麼,我需要實現Pseduo代碼示例:
while(eventQuery):
if commentQueryResult;
$array .= commentQueryResult;
if forumPostQueryResult;
$array .= forumPostQueryResult;
if uploadItemQueryResult;
$array .= uploadItemQueryResult;
endwhile;
return $array; // Combined returned results as one array
我隨後將能夠通過它來訪問數據,只是foreach循環。
我只是不確定將多個結果集合到一個數組中的最佳方式?
或者你可以嘗試,並結合成一個查詢...
$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
}
我將所有的這些對PDO的過程是,這是工作的最佳出路後的下一步儘量減少這一點。
通過連接表是不可能用單個查詢來查詢事件列表和事件類型表?沿着以下幾行的東西:'SELECT * FROM event e INNER JOIN eventType et ON e.eventID = et.eventID' 雖然我也完全有可能誤解了你的問題。 – andrewsi
沒有連接會太複雜,它通過使用php的第一個查詢循環來生成從其他結果返回的數據數組。 – Dan
太複雜?我會說試試我們。至少,我喜歡腦筋急轉彎。 ;) – Paul