php mysql查询多个表

时间:2016-01-07 21:34:20

标签: php mysql

我想知道是否可以从一个表中获取数据来搜索另一个表并输出该数据。示例获取玩家的alliance_id并搜索联盟点击alliance_id并获取联盟名称并输出名称

当前查询

$sql="SELECT * FROM players alliances WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
 echo "<table>
   <tr>
 <th>id</th>
 <th>race_id</th>
 <th>alliance_id</th>
 <th>alliance_role_id</th>
 <th>name</th>
  <th>alliance_name</th>
 </tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";

echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['race_id'] . "</td>";
echo "<td>" . $row['alliance_id'] . "</td>";
echo "<td>" . $row['alliance_role_id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['alliance_name'] . "</td>";
echo "</tr>";

1 个答案:

答案 0 :(得分:2)

您要找的是JOIN

SELECT players.*, alliances.*
FROM players
LEFT JOIN alliances ON players.alliance_id = alliances.id
WHERE players.id = ?

MySQL doc: http://dev.mysql.com/doc/refman/5.7/en/join.html