从代码中,我希望这两个表(个人和信息)来比较它是否具有相同的位置。如果匹配,我想显示评论中所述的个人表中的数据。
$selectall = "SELECT * FROM information";
$stmt = mysqli_query($connection, $selectall);
$compare = "SELECT * FROM personal INNER JOIN information ON personal.location = information.location";
$comparing = mysqli_query($connection, $compare);
while($row = mysqli_fetch_array($stmt)) {
$output .= '<tr>
<td>' .$row['name']. '</td>
<td>' .$row['location']. '</td>
<td>' .$row['postal']. '</td>
</tr>
<tr>
<td>//This is where I want to show the matched data from personal table</td>
</tr>';
}
答案 0 :(得分:0)
我认为您需要的是$comparing
查询的结果,而不是$selectall
。
如果要返回特定列,可以操作SQL以仅返回所需的列。例如:
SELECT column_from_information, other_column_you_want, personal.location FROM personal INNER JOIN information ON personal.location = information.location
您的想法是可以使用前置表名定义列,即personal.name,information.location等。
while($row = mysqli_fetch_array($comparing)) {
$output .= '<tr>
<td>' .$row['name']. '</td>
<td>' .$row['location']. '</td>
<td>' .$row['postal']. '</td>
</tr>
<tr>
<td><!--Matched Data--></td>
</tr>';
}
答案 1 :(得分:0)
如果您希望获取information
中的所有内容,即使它在personal
中没有匹配项,也请使用外部联接。对于不匹配的行,personal
中的列将包含null
。
您应该明确选择所需的列。如果您使用SELECT *
并且两个表中都有相同名称的列,则$row['columnname']
会从第二个表中获取值,如果没有匹配则为null
。由于您需要第一个表中的值,请专门选择它。
$compare = "SELECT i.name, i.location, i.postal, p.somecolumn, p.anothercolumn FROM information AS i
LEFT JOIN personal AS p
ON p.location = i.location";
$comparing = mysqli_query($compare);
while ($row = mysqli_fetch_assoc($comparing)) {
$output .= '<tr>
<td>' .$row['name']. '</td>
<td>' .$row['location']. '</td>
<td>' .$row['postal']. '</td>
</tr>
<tr>
<td>' . $row['somecolumn'] . '</td>
<td>' . $row['anothercolumn'] . '</td>
</tr>';
}