Php 查询表,然后为每个结果查询另一个表,然后。。。等
我需要查询一个数据库,其中Php 查询表,然后为每个结果查询另一个表,然后。。。等,php,mysql,Php,Mysql,我需要查询一个数据库,其中location=$location。这将返回一些用户ids 然后我需要查询另一个数据库,其中user\u id=以前的user\u id结果。这将找到game\u ids 然后,我需要用这些game\u ids查询另一个表,以获得每个游戏的名称(每个游戏名称都分配了一个id) 这就是我所拥有的: if (isset($_POST['location'])) { $location = $_POST['location']; $quer
location=$location
。这将返回一些用户id
s
然后我需要查询另一个数据库,其中user\u id
=以前的user\u id
结果。这将找到game\u id
s
然后,我需要用这些game\u id
s查询另一个表,以获得每个游戏的名称(每个游戏名称都分配了一个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>";
}
if(isset($\u POST['location'])){
$location=$_POST['location'];
$query=mysql\u query(“从位置为“$location”的用户中选择*)或die(mysql\u error());
回声“”;
while($row=mysql\u fetch\u array($query)){
foreach(将(“,”,$row['user\u id'])分解为$users){
echo“- ”$row['user_name']。“
- ”;
//在这里,我需要查询另一个表,其中user_Id=$user(在上一次查询中找到的每个用户)
//这将找到多个游戏id(作为$game),然后我需要查询另一个表来找到game_id=$game
//输出游戏名称
回声“
”;
}
}
回声“
”;
}
听起来很复杂。有更简单的方法吗?这样的查询将生成
位置、用户id、游戏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
}
学习在数据库查询中使用联接,您会发现它的效率要高得多,不过如果您规范化了数据库,而不是将多个值存储在诸如user_id之类的列中,这也会有所帮助,现在您已经接受了,还要了解
内部连接
和左连接
在使用和内存方面的差异,并根据您的使用情况使用适当的连接。