我想选择一些存储在MySQL数据库中的信息。例如,我有2个表gameTable和playerTable。现在我想获得gameTable并获得这些玩家的名字和等级。我该怎么办?
这是我到目前为止所做的,它有效,但我不确定这是最有效的方式。我是否需要为每个被引用的行创建连接?
<?php
include ('connect.php');
$result = mysqli_query($connect,
"SELECT gameTable.id,
playerTable1.name AS name1, playerTable1.level AS level1,
playerTable2.name AS name2, playerTable2.level AS level2,
playerTable3.name AS name3, playerTable3.level AS level3,
playerTable4.name AS name4, playerTable4.level AS level4
FROM gameTable
JOIN playerTable AS playerTable1 ON gameTable.P1_id = playerTable1.id
JOIN playerTable AS playerTable2 ON gameTable.P2_id = playerTable2.id
JOIN playerTable AS playerTable3 ON gameTable.P3_id = playerTable3.id
JOIN playerTable AS playerTable4 ON gameTable.P4_id = playerTable4.id
");
while ($record = mysqli_fetch_array($result))
{
echo $record['id'] . " - "
. $record['name1'] . " - " . $record['level1'] . " - "
. $record['name2'] . " - " . $record['level2'] . " - "
. $record['name3'] . " - " . $record['level3'] . " - "
. $record['name4'] . " - " . $record['level4'] . "<br>";
}
?>
第二个问题,我的数据库设置为MyISAM。将它更改为InnoDB会有帮助吗?或者这仅对更新删除等有用。在您的数据库中而不是用于获取数据?
答案 0 :(得分:0)
我会用字符串这样做(参考评论问题,而不是原始问题)。这为内存中的每个位置保留了一个字符串空间。这样可以节省为中间字符串分配值的开销,并且可以节省内存,甚至可以加快执行时间,因为字符串连接有时是一个非常缓慢的过程。
$myarr = array();
while ($record = mysqli_fetch_array($result))
{
$myarr[] = $record['id'] ;
$myarr[] = " - " ;
$myarr[] = $record['name1'] ;
$myarr[] = " - " ;
$myarr[] = $record['level1'];
$myarr[] = " - ";
$myarr[] = $record['name2'];
$myarr[] = " - ";
$myarr[] = $record['level2'];
$myarr[] = " - ";
$myarr[] = $record['name3'];
$myarr[] = " - ";
$myarr[] = $record['level3'];
$myarr[] = " - ";
$myarr[] = $record['name4'];
$myarr[] = " - ";
$myarr[] = $record['level4'];
$myarr[] = "<br>";
}
echo implode('',$myarr);
unset($myarr);