当device_transactions
表中没有相应的记录,或者在device_transactions
表中有相应的记录时,我希望状态列显示值“自由”returned_date空白字段
当device\u transactions
表在devices表中没有相应的记录时,如何打印第4行?
这两个数据表
表设备:
表1设备\u事务:
<table id="myTable">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$sql = $conn->prepare("SELECT devices.id, devices.name, device_transactions.returned_date
FROM devices, device_transactions WHERE devices.id = device_transactions.device_id ");
$sql->execute();
$result = $sql->setFetchMode(PDO::FETCH_ASSOC);
foreach ($sql->fetchAll() as $row) { ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php
if($row['returned_date'] !== null ){
echo "free";
}
else{
echo "borrowed";
}
?></td>
</tr>
<?php }
?>
</tbody>
</table>
您希望使用左连接
,而不是来自设备、设备\u事务的(这是一个
内部连接
)。
SELECT devices.id, devices.name, device_transactions.returned_date
FROM devices
LEFT JOIN device_transactions ON devices.id = device_transactions.device_id
只需使用简单的左连接,您将获得所有记录:
SELECT d.id as deviceid, d.name as devicename, c.returned_date as returndate
FROM device d
LEFT JOIN device_transactions c ON c.device_id = d.id;
看到它在这里工作了吗
https://dbfiddle.uk/?rdbms=mysql_8.0