2011-12-28 109 views
0

我需要查詢一個數據庫,其中location = $location。這將返回一些user_id s。查詢表,然後查詢每個結果的另一個表,然後... etc

然後我需要查詢另一個數據庫,其中user_id =那些之前的user_id結果。這會發現game_id s。

然後我需要查詢與game_id是另一個表來獲得每場比賽的名稱(每個遊戲名被分配一個ID)。

這是我有:

if (isset($_POST['location'])) { 
     $location = $_POST['location']; 
     $query = mysql_query("SELECT * FROM users WHERE location = '$location'") or die(mysql_error()); 

     echo "<ul>"; 
     while ($row = mysql_fetch_array($query)) { 
      foreach (explode(", ", $row['user_id']) as $users) { 
       echo "<li>" . $row['user_name'] . "<ul><li>"; 
       //this where I need I need to query another table where user_Id = $user (each user found in previous query) 
//this will find multiple game id's (as $game) , I then need to query another table to find game_id = $game 
// output name of game 
       echo "</li></ul></li>"; 
      } 
     } 
     echo "</ul>"; 
     } 

聲音複雜。有一種更簡單的方法嗎?

+5

學習在數據庫查詢中使用JOIN,你會發現它效率更高如果你規範化你的數據庫,而不是像在user_id – 2011-12-28 16:49:33

+0

這樣的列中存儲多個值,那麼也會有所幫助謝謝,iv完成它! – AJFMEDIA 2011-12-28 17:13:42

回答

0

這樣的查詢將產生location, user_id, game_id表。在你的SQL查詢中付出儘可能多的努力,以便你可以通過代碼輕鬆應對:

$query = mysql_query("SELECT game_name FROM another_table \ 
         JOIN users \ 
         JOIN games \ 
         WHERE users.location = '$location'") 
     or die(mysql_error()); 
while ($row = mysql_fetch_array($query)) { 
    echo $row['game_name']; //Here is the game name 
} 
+0

現在你已經接受了,也學習了'INNER JOIN'和'LEFT JOIN'在使用和內存上的區別,並根據你的使用情況使用適當的連接。 – Hossein 2012-01-06 09:42:11

相關問題