【发布时间】:2022-01-22 23:06:21
【问题描述】:
当device_transactions表中没有对应的记录,或者device_transactions表中有对应的记录有returned_date空白字段时,我希望status列显示值“free”
当device_transactions 表在设备表中没有对应记录时,如何打印第 4 行?
2个数据表
桌面设备:
| id | name |
|---|---|
| 1 | Laptop01 |
| 2 | Laptop02 |
| 3 | Laptop03 |
| 4 | Laptop04 |
表 device_transactions:
| id | device_id | start_transaction_plan | end_transaction_plan | returned_date |
|---|---|---|---|---|
| 1 | 1 | 2021-12-10 14:20:43 | 2021-12-12 07:00:00 | 2021-12-12 9:30:23 |
| 2 | 2 | 2021-12-11 10:10:20 | 2021-12-15 15:30:00 | 2021-12-16 7:30:45 |
| 3 | 3 | 2021-12-12 19:03:00 | 2021-12-21 08:00:00 | NULL |
<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>
【问题讨论】:
-
您尝试过什么来解决问题?
$row['returned_date']包含哪些出乎你意料的内容? -
我希望结果返回#row4 laptop04 |免费,但由于它在 device_transactions 表中没有记录,我不知道该怎么做。
-
使用
LEFT JOIN连接设备和设备事务表以从设备表中获取所有结果。如果 device_transactions 表中没有记录,则其余值为NULL。